Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
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
add comment

2 Answers

up vote 5 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
y
$ sudo -s 'if [ -n x ]; then echo y; fi'
y
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
1  
Yes, so long as it's quoted or escaped properly. See my edit. –  Kevin Jun 12 '12 at 3:05
add comment

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
add comment

Your Answer

 
discard

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.