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"
   echo "i dont have sudo"

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.


You can use:

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

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.

  • 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 '13 at 17:38
  • @StevenKath It does the same thing, but thanks for suggestion. I improved my answer since your suggestion is more elegant. – Radu Rădeanu Oct 12 '13 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 '15 at 0:23
  • 1
    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. – nyuszika7h Jan 1 '19 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.