Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 928
Aquarius_Girl Avatar asked Aug 07 '14 06:08

Aquarius_Girl


People also ask

What does bash syntax error near unexpected token `(' mean?

bash: syntax error near unexpected token. It means you are typing a mongo shell command into bash shell. You must connect to your cluster with the mongo command first. system (system) closed September 14, 2022, 12:52am #3.

What does syntax error near unexpected token?

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

What is syntax error in bash?

The syntax error is because of (). Remove () from the file like this: #!/bin/bash function hello { echo "Hello world" } or you can just run the following command to edit the file for you: sed -i 's/() //g' hello.sh. You should now be able to run the file with the desired result.


3 Answers

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

like image 185
tripleee Avatar answered Nov 15 '22 04:11

tripleee


for is an internal function (not to be confused with functions) of a shell that's why you can't call it. You should explicitly call the binary of the shell that runs with the code like this:

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

With bash:

sudo bash -c 'for n in {1..60}; do echo "$n"; sleep 1; sync; done'
sudo bash -c 'for ((n = 1; n <= 60; ++n)); do echo "$n"; sleep 1; sync; done'
like image 39
konsolebox Avatar answered Nov 15 '22 03:11

konsolebox


It's because the fist semicolon terminates the sudo command, which will make do a new command. The easiest way to fix this is to put the loop inside a file and execute it, like

sudo /bin/bash ./myfile
like image 34
Some programmer dude Avatar answered Nov 15 '22 05:11

Some programmer dude