Ubuntu – How to check if sudo password has been entered for this terminal session

command linesudo

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.

Best Answer

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.