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

后端 未结 6 886
别跟我提以往
别跟我提以往 2021-01-30 10:33

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          


        
6条回答
  •  执笔经年
    2021-01-30 11:15

    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"
    

提交回复
热议问题