Take the 2-minute tour ×

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?

share|improve this question
add comment

3 Answers

up vote 10 down vote accepted

sudo wants a program (+arguments) as a parameter, not a piece of shell script. You can do this, though:

sudo -i -u user sh -c 'for i in /dir; do echo $i; done'

Note the single quotes. If you used double quotes, your shell would try to expand the $i before sudo (or, rather, the shell run by it) ever sees it.

share|improve this answer
you got it! Good luck to all. –  shellter Jun 4 '12 at 22:13
That did the trick, thanks! –  Axl Jun 4 '12 at 22:13
According to this, every output file will be written/saved in the home directory of the specified user. What if I want the output to be written in a specific one? –  Alessandro Cuttin Dec 31 '13 at 11:39
@AlessandroCuttin the example doesn't write any output files. Seems like your comment is about an unspecified variation on the question...? –  Jan Krüger Jan 6 at 12:48
add comment

You can try sudo bash -c 'commands here'

share|improve this answer
add comment

Put the sudo inside the loop:

for i in /dir; do
    sudo -u user somecommand $i

This won't work without extra steps if you need the other user's permissions to generate the glob for the loop, for example.

share|improve this answer
add comment

Your Answer


