qrest
qrest

Reputation: 3083

How can I execute a series of commands in a bash subshell as another user using sudo?

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?

Upvotes: 51

Views: 43274

Answers (5)

Chaitu Nookala
Chaitu Nookala

Reputation: 213

If you would like to get syntax highlighting from your editor, not use quotes around your code, and have proper indentation, you can write your commands in a function and send it to bash using the declare command:

function run_as_root() {
    whoami
    id
    echo $USER
}

sudo bash -c "$(declare -f run_as_root); run_as_root"

Upvotes: 9

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136515

You can pass the commands as standard input into sudo'ed bash with a here document:

sudo bash <<"EOF"
whoami
id
EOF

This way there is no need to fiddle with correct quoting, especially if you have multiple levels, e.g.:

sudo bash <<"EOF"
whoami
echo $USER ~
sudo -u apache bash <<"DOF"
whoami
echo $USER ~
DOF
EOF

Produces:

root
root /root
apache
apache /usr/share/httpd

(Note that you can't indent the inner terminator — it has to be alone on its line. If you want to use indentation in a here document, you can use <<- instead of <<, but then you must indent with tabs, not spaces.)

Upvotes: 71

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

You can use any character except ' itself inside the single quotes. If you really want to have a single quote in that command, use '\'' (which technically is: end single-quote literal, literal ' character, start single-quoted literal; but effectively this is a way to inject a single quote in a single-quoted literal string).

Upvotes: 68

schemacs
schemacs

Reputation: 2891

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.

Upvotes: -3

kit.yang
kit.yang

Reputation: 2798

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 '()'.

Upvotes: -2

Related Questions