syntax error near unexpected token `do' when run with sudo

Aquarius_Girl picture Aquarius_Girl · Aug 7, 2014 · Viewed 21.7k times · Source

From here: http://www.sat.dundee.ac.uk/psc/watchdog/watchdog-testing.html

for n in $(seq 1 60); do echo $n; sleep 1; sync; done

I get:

:~$ sudo for n in $(seq 1 60); do echo $n; sleep 1; sync; done  
bash: syntax error near unexpected token `do'

Answer

tripleee picture tripleee · Aug 7, 2014

The shell parses the command line and because for looks like an argument to sudo, you basically get a do without a for.

To fix it, run the loop in a subshell, either as a separate script, or like this;

sudo sh -c 'for n in $(seq 1 60); do echo "$n"; sleep 1; sync; done'

Better yet, avoid running anything unnecessary as a privileged user:

for n in $(seq 1 60); do echo "$n"; sleep 1; sudo sync; done

The first sudo will require a password, but subsequent iterations should have it cached, with the default settings on most distros.

If you are on Bash, you can use {1..60} instead of $(seq 1 60). Obviously, if you want to use Bash-specific syntax inside the single quotes in the first example, you need bash -c instead of sh -c