In bash I can do the following:

if [ -f /tmp/test.txt ]; then echo "true"; fi

However, if I add sudo in front, it doesn't work anymore:

sudo if [ -f /tmp/test.txt ]; then echo "true"; fi
-bash: syntax error near unexpected token `then'

How can I make it work?

  • 1
    See this answer on SO... – jasonwryan Jun 12 '12 at 2:57
  • It is better practice to sudo only the test and/or only the echo. Not the entire if statement. – jippie Jun 12 '12 at 6:32
  • You mean if sudo test? Yes, that'd be better. I can't use test without the if, because it sets the exit code otherwise. – m33lky Jun 12 '12 at 19:07

sudo executes its argument using exec, not via a shell interpreter. Therefore, it is limited to actual binary programs and cannot use shell functions, aliases, or builtins (if is a builtin). Note that the -i and -s options can be used to execute the given commands in a login or non-login shell, respectively (or just the shell, interactively; note that you'll have to escape the semicolons or quote the command).

$ sudo if [ -n x ]; then echo y; fi
-bash: syntax error near unexpected token `then'
$ sudo if [ -n x ]\; then echo y\; fi
sudo: if: command not found
$ sudo -i if [ -n x ]\; then echo y\; fi
$ sudo -s 'if [ -n x ]; then echo y; fi'
  • So, if I use -i or -s, the if-statement will be evaluated properly? – m33lky Jun 12 '12 at 3:02
  • 2
    Yes, so long as it's quoted or escaped properly. See my edit. – Kevin Jun 12 '12 at 3:05

Try calling the line as a string argument through the shell.

sudo /bin/sh -c 'if [ -f /tmp/test.txt ]; then echo "true"; fi'

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.