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"
    echo "OK. You do have the neccessary sudo rights"

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
  • 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

The normal way works nicely for me:

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

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

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

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