Howto switch / chage user id witin a bash script to execute commands in the same script?

12

6

Is there a way to switch user identity within a script (executed as root as part of an installation process) to execute some commands without calling an external script, then return to root to run other commands?

Sort of:

#!/bin/bash
some commands as root
SWITCH_USER_TO user
some commands as user including environment variables checks, without calling an external script
SWITCH_USER_BACK
some other stuff as root, maybe another user id change...

a1an

Posted 2012-08-30T09:07:04.413

Reputation: 275

Duplicate of How do I use su to execute the rest of the bash script as that user?

– Dan Dascalescu – 2014-07-11T11:36:11.283

You should have a look at this answer http://stackoverflow.com/a/17758312/1243547

– Klaus – 2017-03-09T10:23:40.027

Answers

26

No. But you can use sudo to run a shell and use a heredoc to feed it commands.

#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami

Ignacio Vazquez-Abrams

Posted 2012-08-30T09:07:04.413

Reputation: 100 516

This answer is better than all the answers in the question that this one duplicates.

– Dan Dascalescu – 2014-07-11T10:36:30.217

1I almost wonder, if I were to do this, I would not use EOF, and instead change the name of the heredoc to SUDO. That way I would remember that I'm running as super user inside the containing code. – Joe Heyming – 2016-03-09T05:27:54.033

For some reason, it seems that setting vars in the heredoc command, the vars are not set. If I try BLA="something" and then eg: echo "In: $BLA", it seems BLA is empty – Efren – 2018-09-12T07:34:37.610

This surely does the job in keeping things together in the same script and can also use command substitution if everything is wrapped with the closing bracket one line after EOF – a1an – 2012-08-30T13:01:45.527