views:

134

answers:

4

Hello -- I'm writing a bash script that needs to sudo multiple commands. I can do this:

( whoami ; whoami )

but I can't do this:

sudo ( whoami ; whoami )

How do I solve this?

+9  A: 

Run a shell inside sudo: sudo bash -c 'whoami; whoami'

Gilles
A: 

The Brackets means that execute the command in a new bash.It execute the command with the interval of semicolon.Just use the code below instead.

(sudo whoami;sudo whoami)

BYW:the space is not necessary when using '()'.

kit.yang
-1 Also a bad idea
siride
+5  A: 

You can also pipe the commands into sudo'ed bash:

sudo bash <<EOF
whoami
id
EOF
Maxim Yegorushkin
A: 

sudo only asks for your passwd the first time.The passwd answered is valid for about 5 minutes by default.You can change this value as this told.So just worry about the passwd prompt at the beginning of your script,then you can use sudo through out. changing Defaults:user_name timestamp_timeout's value to -1 may be a security hole on your system.

schemacs
-1 This is just a disaster waiting to happen
siride
What I mean is sudo only prompts for password at the first time.no prompt within 5 minutes or more.How long will your script run?exit with 5 minutes?You should never change the default value to -1.Few cmds require root permission.just use sudo foo anywhere in your script at each line,or connected by comma.
schemacs