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

后端 未结 6 938
别跟我提以往
别跟我提以往 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:09

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

提交回复
热议问题