I want to run a simple for loop command with sudo, but it isn’t working:
sudo -i -u user for i in /dir; do echo $i; done
I get the following error:
-bash: syntax error near unexpected token `do'
Probably a very simple thing I am overlooking. Any help?
sudo wants a program (+arguments) as a parameter, not a piece of shell script. You can do this, though:
Note the single quotes. If you used double quotes, your shell would try to expand the
$ibefore sudo (or, rather, the shell run by it) ever sees it.PS. a separate problem, as pointed out in a comment (only six years later), is that if you want to iterate over the files in a directory, the proper syntax is
for i in /dir/*.foraccepts a list, and/diris a list… with one item./dir/*expands to a list of files in/dirdue to wildcard expansion.