22

As said in the headline, I need to check if the sudo password has been entered for this terminal session in a shell (aka, if I have sudo rights now).

If I have it, I would like to do one thing and if I don't have it, then it should not prompt me for it, just let me do another thing.

So in pseudo code it looks like this:

if (sudo = true)
   echo "i got sudo"
else
   echo "i dont have sudo"
fi

But all commands I've found for this always prompts me for the sudo password when trying to check.

Basic idea is that the script can (and will) ask for sudo password several places, but i don't want to print out "The script will now ask for your sudo password." if it has already been entered (which means it wont ask for the sudo password).

Hope someone can help me.

1 Answer 1

31

You can use:

if sudo -n true 2>/dev/null; then 
    echo "I got sudo"
else
    echo "I don't have sudo"
fi

The -n (non-interactive) option prevents sudo from prompting the user for a password. If a password is required for the command to run, sudo will display an error message (redirected to /dev/null) and exit. If the password is not required, then this expression is true: sudo -n true 2>/dev/null.

6
  • 4
    It doesn't really help to echo a string and compare it to another string, the exit code from sudo is enough for the test. The first line can be if sudo -n true 2>/dev/null; then
    – Steven K
    Oct 12, 2013 at 17:38
  • @StevenKath It does the same thing, but thanks for suggestion. I improved my answer since your suggestion is more elegant. Oct 12, 2013 at 17:50
  • 2
    I know this is AskUbuntu, but this doesn't work in MacOSX, sudo -n always returns 0 so checking the return code fails. I'm saying this here because I've searched for this and this page comes up in Google.
    – Normadize
    Mar 10, 2015 at 0:23
  • 2
    This is a bad idea as it will send mail to root every time a password would be required if mail_badpass is enabled in sudoers. Jan 1, 2019 at 14:32
  • @Normadize Working in MacOSX Monterey. sudo caches passswords/usage for a while, could it be the case? On the other hand, that is the Achilles of this script leading to frequent false positives. May 10, 2022 at 13:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .