Possible Duplicate:
Switching to superuser while shell script is running

I need to switch users in a script and keep executing commands. I thought -c would work but i don't know how to use it properly nor any idea how to do this. I wrote

bash -c "su user && command arg1 arg2"

It tried to execute the command after i typed in exit. I tried setting UID and executing it but the app seems to know what user i am (root) and does things which i can not access as the user i am targeting so it looks like i really do need to figure out how to switch users and continue to execute bash code.

marked as duplicate by Gilles, Renan, jasonwryan, Mat, Kevin Nov 12 '12 at 1:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • please clarify. you want to run a command as a user different than your shell, but you still want to be able to use your shell? or you want to execute different portions of a script as different users? – Tim Kennedy Nov 9 '12 at 5:06
  • @TimKennedy I'd like to run different portions of the script as a different user – user4069 Nov 9 '12 at 5:20
  • 2
    You should look into sudo su vbox -c "some command", probably setup a few lines in your /etc/sudoers. This is more lightweight than the ssh solution. If you hadn't already accepted within minutes from asking your question, I would have taken the effort to explain a bit more. – jippie Nov 9 '12 at 7:44

Your best option is to generate ssh keys using ssh-keygen and add the public key into the user you want to become and then use the private key in the script to connect, so your script would effectively be something like this:

ssh -i ~/.ssh/userA_id_rsa userA@localhost command arg1 arg2

This requires the SSH Daemon to be running on the system (which most distros install by default, but may not have running).