Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sudo with for loop

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?

like image 577
Axl Avatar asked Jun 04 '12 22:06

Axl


People also ask

Can you use sudo in script?

In Linux, the sudo command allows us to execute a command or script as the superuser. However, by default, the sudo command works in an interactive mode.

How do I run a sudo script?

Running a Specific Script as Another User. Before we can execute scripts as other users with sudo, we'll need to add the current user to the sudoers file. To do that, we'll use the visudo command to safely edit the /etc/sudoers file. The command above echo the rule and pipe the rule into the visudo command.

Can we use for loop in shell script?

A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. For example, you can run UNIX command or task 5 times or read and process list of files using a for loop. A for loop can be used at a shell prompt or within a shell script itself.

How do I run a loop in Linux?

The basic syntax of a for loop is: for <variable name> in <a list of items>;do <some command> $<variable name>;done; The variable name will be the variable you specify in the do section and will contain the item in the loop that you're on.


3 Answers

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.

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/*. for accepts a list, and /dir is a list... with one item. /dir/* expands to a list of files in /dir due to wildcard expansion.

like image 144
Jan Krüger Avatar answered Oct 11 '22 18:10

Jan Krüger


You can try sudo bash -c 'commands here'

like image 28
BLaZuRE Avatar answered Oct 11 '22 18:10

BLaZuRE


Put the sudo inside the loop:

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

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

like image 1
evil otto Avatar answered Oct 11 '22 18:10

evil otto