3

I am trying to test if a user has the required sudo rights to run a command as another user without providing a password. What I have is this

 sudo -u other-user -n true
  if [ $? -ne 0 ]; then
    echo "ERROR: You don't have the neccessary sudo rights"
  else
    echo "OK. You do have the neccessary sudo rights"
  fi

However, the scripts prints this error message if sudo requires a password

  sudo: sorry, a password is required to run sudo

Is it possible to suppress this error message?

I have tried to redirect both system err and system out but the error message still appears.

  sudo -u other-user -n true > /dev/null 2>&1

closed as off-topic by Patrick, slm Aug 28 '14 at 0:10

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Patrick, slm
If this question can be reworded to fit the rules in the help center, please edit the question.

  • sudo -u other-user -n true 2>/dev/null sends standard error to nothing, null binary. A similar situation which I've described here: serverfault.com/questions/550107/… – Valentin Bajrami Aug 27 '14 at 14:38
  • Thanks. Now i wonder why not "> /dev/null 2>&1" didn't also send standard error to nothing, but thats another question ... – sstendal Aug 27 '14 at 14:41
  • sudo -n true >/dev/null 2>&1 works perfectly fine for me (immediately returns status 1 & nothing is displayed). What version of sudo, and distro are you using? – Patrick Aug 27 '14 at 14:46
  • Normally that should have worked. See mywiki.wooledge.org/BashFAQ/… which explains everything about file descriptors including portability – Valentin Bajrami Aug 27 '14 at 14:48
1

The normal way works nicely for me:

$ sudo -u test -n true  
sudo: a password is required
$ echo $?                                   
1
$ sudo -u test -n true >/dev/null 2>&1
$ echo $?                                   
1

But if for whatever reasons it does not help for you, try these:

$ { sudo -u test -n true ; } >/dev/null 2>&1
$ echo $?                                   
1
$ ( sudo -u test -n true ) >/dev/null 2>&1
$ echo $?                                 
1

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