Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

some commands as root
some commands as user including environment variables checks, without calling an external script
some other stuff as root, maybe another user id change...
share|improve this question
up vote 16 down vote accepted

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

sudo -u someuser bash << EOF
echo "In"
echo "Out"
share|improve this answer
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. – Dan Dascalescu Jul 11 '14 at 10:36
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 9 at 5:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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