18

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...
Dan Dascalescu
  • 3,769
  • 6
  • 35
  • 53
a1an
  • 335
  • 1
  • 2
  • 9
  • Duplicate of [How do I use su to execute the rest of the bash script as that user?](http://stackoverflow.com/questions/1988249/how-do-i-use-su-to-execute-the-rest-of-the-bash-script-as-that-user) – Dan Dascalescu Jul 11 '14 at 11:36
  • You should have a look at this answer http://stackoverflow.com/a/17758312/1243547 – Klaus Mar 09 '17 at 10:23

1 Answers1

34

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
  • 111,361
  • 10
  • 201
  • 247
  • 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 Aug 30 '12 at 13:01
  • This answer is better than all the answers in [the question that this one duplicates](http://superuser.com/questions/93385/run-part-of-a-bash-script-as-a-different-user). – Dan Dascalescu Jul 11 '14 at 10:36
  • 1
    I 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 Mar 09 '16 at 05:27
  • 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 Sep 12 '18 at 07:34
  • In my CentOS 7 no `In` nor `someuser` is printed :/ Any insight why? – lucasvc Feb 08 '21 at 15:56