Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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
up vote 6 down vote accepted

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'
share|improve this answer
So, if I use -i or -s, the if-statement will be evaluated properly? – m33lky Jun 12 '12 at 3:02
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'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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