Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
qrest Avatar asked Aug 08 '10 17:08

qrest


People also ask

How do I run a command as another user in Unix?

The su command lets you switch the current user to any other user. If you need to run a command as a different (non-root) user, use the –l [username] option to specify the user account. Additionally, su can also be used to change to a different shell interpreter on the fly.


2 Answers

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

like image 78
Maxim Egorushkin Avatar answered Nov 09 '22 02:11

Maxim Egorushkin


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

like image 44
Gilles 'SO- stop being evil' Avatar answered Nov 09 '22 02:11

Gilles 'SO- stop being evil'