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'
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.
The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.
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.
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
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With