1

I want to continue the execution of the script after change user, the script would be something like below

echo "xauth add" `xauth list | grep ${DISPLAY:10:2}` >> test.sh

sudo su

./test.sh

script test.sh should be run after changing the user, but after "sudo su", the command ./test.sh wouldn't run. Can we make this possible

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
karra
  • 11

3 Answers3

3

You can not change user identity in the middle of a script and then continue running the script as that new user.

You may however execute another command or script as another user using sudo:

sudo ./test.sh

If more than one command needs to be run as the other user, then add these commands to the test.sh script, or, if it's just one or two more things that needs to be run, use

sudo sh -c './test.sh; other_command'

Control will be handed back to the parent script (the one calling sudo) as soon as whatever sudo is executing has terminated.

Kusalananda
  • 333,661
1

You can change the user mid-script, but this requires feeding the input to the shell and may not be portable to old and eldritch flavors of sh) and is probably a bad idea:

$ cat changemidscript
who am i
sudo -i
who am i
$ bash < changemidscript
jhqdoe   tty??    Oct  5 14:21 
root     tty??    Oct  5 14:21 
$ 

However! bash changemidscript or ./changemidscript will both not behave the same as the above, which again points to this being a bad idea, as only the feed-the-input-in-via-standard-input will allow the user change and then the subsequent commands as that new user. (Did I mention you probably want to use a different way? You should!)

strace may help show why this method works; shells may take pains to read the input line by line, so will either read in one character increments (so they can stop reading when a \n is found) or will read into a buffer and then back the file handle up to the beginning of the next line for each line, depending on where the \n are found.

thrig
  • 34,938
  • It may be worth mentioning that the shell executing that last line of the script is the shell started by sudo -i, not the shell originally executing the script. – Kusalananda Feb 28 '19 at 15:17
0

EDIT: Actually, you want to do either sudo su -l -c ./test.sh (if you need a login shell) or sudo ./test.sh.

Look at the man pages for su and sudo.

thecarpy
  • 3,935