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

Viewed 38097

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?

6 Answers

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"
Related