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

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.

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.

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

  • 1
    Or just sudo ./test.sh? Why su to root from root(sudo)? – Jeff Schaller Oct 5 '17 at 19:36
  • 4
    Aieee.. Please don't continue the cargo cult construct sudo su – roaima Oct 5 '17 at 19:36
  • @jeff Schaller yes, "sudo su -c ./test.sh". is running the above command in root but not changing to root user. I want to change to root user because some more set of commands that need to be executed – karra Oct 5 '17 at 19:46
  • @roaima I read the related forum, thank's for sharing I will change the script little built – karra Oct 5 '17 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.