How do I find out if my sudoer privilege timed out?
Use the option -n
to check whether you still have privileges; from man sudo
:
-n, --non-interactive
Avoid prompting the user for input of any kind. If a password is required for the command to run, sudo will display an error message and exit.
For example,
sudo -n true 2>/dev/null && echo Privileges active || echo Privileges inactive
Be aware that it is possible for the privileges to expire between checking with sudo -n true
and actually using them. You may want to try directly with sudo -n command...
and in case of failure display a message and possibly retry running sudo
interactively.
Edit: See also ruakh's comment below.
Run:
sudo -nv
If your sudo privileges have timed out, this will exit with an exit code of 1 and output:
sudo: a password is required
If you have valid cached credentials, this command will succeed and output nothing.
So, to put it all together, here's a scriptlet that will silently check if you have valid cached credentials:
if sudo -nv 2>/dev/null; then
echo "no sudo password required"
else
echo "sudo password expired"
fi
As other answers/comments mentioned, the -v
option ("validate") to sudo silently renews cached credentials if there are any or else prompts for authentication in order to generate cached credentials, and the -n
option ("non-interactive") prevents sudo from generating any interactive prompts, such as the authentication prompt.