17

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

1 Answer 1

32

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
5
  • 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, 2012 at 13:01
  • This answer is better than all the answers in the question that this one duplicates. Jul 11, 2014 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. Mar 9, 2016 at 5: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, 2018 at 7:34
  • In my CentOS 7 no In nor someuser is printed :/ Any insight why?
    – lucasvc
    Feb 8, 2021 at 15:56

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.