Executing SU in a bash script

Fred Finkle asked:

I’m running a remote bash script (using ssh -t ‘bash doscript.sh’). In “doscript.sh” I have a sudo su anotheruser. At that point, the script seems to push a shell and I’m left in that “interactive” script and the rest of my script (doscript.sh) doesn’t run unless I type “exit”. Is there a workaround that gets around this problem?

Thanks in advance.

Here is the contents of my test script “doscript.sh”:

sudo su diy

My answer:

sudo starts a shell unless you instruct it otherwise.

It looks like you actually want to run this script as another user. To do that, try something like this:

if [ `id -nu` != diy ]; then
    sudo -u diy $0 # Re-run this script as user diy
    # Everything you want to do goes here

Keep in mind that /etc/sudoers must be set up to allow the original user to run this script as the new user.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.