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 cd pwd whoami exit whoami
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:
#!/bin/bash
if [ `id -nu` != diy ]; then
sudo -u diy $0 # Re-run this script as user diy
else
# Everything you want to do goes here
fi
Keep in mind that /etc/sudoers
must be set up to allow the original user to run this script as the new user.
Attribution
Source : Link , Question Author : Fred Finkle , Answer Author : Michael Hampton