Sudo - is there a command to check if I have sudo and/or how much time is left?

I know this is a really old question but here is I did in a script today. Assuming that being sudo means being able to run any command as sudo (or, at least, uptime)

CAN_I_RUN_SUDO=$(sudo -n uptime 2>&1|grep "load"|wc -l)
if [ ${CAN_I_RUN_SUDO} -gt 0 ]
then
    echo "I can run the sudo command"
else
    echo "I can't run the Sudo command"
fi

However, if your user has restrictions in the visudo, this check will not be enough, e.g., if your user can only use the make command. Try running some command that you know will work. You may add the filter grep -v Sorry, e.g.: $(sudo -n uptime 2>&1|grep "load" | grep -v Sorry|wc -l) for avoiding those false positives.


The -n option is available in newer versions of sudo, but as you stated that's not an option. There's no real way to do what you're looking for short of just trying sudo and seeing if it comes back with a prompt for a password. If your concern is you want a visual indication, why not start do sudo /bin/bash to start a root bash session? Note that this is insecure, but it's also somewhat insecure if someone realizes your prompt changes on sudo.


To simplify the answer given by @wags007

if sudo -n true
then
  sudo id
else
  echo "sorry, but did not want to bother you"
fi

However, if in your https://www.sudo.ws/man/1.8.15/sudoers.man.html configuration you have defaults mail_badpass there will be a mail sent for every test that results in false (would have prompted). To avoid such nuisance change that part of your sudoers file to

Defaults       mail_badpass
Defaults!      /bin/true !mail_badpass

As a result security alert mails are send for all commands except /bin/true. Well yes, somebody could now try to brute force a password by calling sudo true an unlimited number of times without any security alert mail being sent.

Note: Always use visudo instead of your favorite editor to edit the sudoers file. Failing to do so you risk being locked out.

Tags:

Linux

Bash

Sudo