Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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...
share|improve this question

1 Answer 1

up vote 7 down vote accepted

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
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 at 10:36

Your Answer

 
discard

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.