Sudo – How to Check if Sudoer Privilege Timed Out

sudo

I'm working on a script that runs a command as sudo and echoes a line of text ONLY if my sudo privileges have timed out, so only if running a command with sudo would require my user (not root) to type its password again.

How do I verify that? Mind that $(id -u) even when running as sudo will return my current user id so that can't be check to match it with 0…

I need a method that would check this quietly.

Best Answer

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.

Related Question