25

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?

3
  • 1
    See this answer on SO...
    – jasonwryan
    Jun 12, 2012 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, 2012 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, 2012 at 19:07

2 Answers 2

17

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
2
  • So, if I use -i or -s, the if-statement will be evaluated properly?
    – m33lky
    Jun 12, 2012 at 3:02
  • 2
    Yes, so long as it's quoted or escaped properly. See my edit.
    – Kevin
    Jun 12, 2012 at 3:05
16

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

sudo /bin/sh -c 'if [ -f /tmp/test.txt ]; then echo "true"; fi'
1
  • this helped me debug!
    – Flion
    May 19, 2020 at 9:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .