Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

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 –  acidzombie24 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

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer

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