Switching Users in a bash Script

Here are some techniques for switching users in a bash script.

su username -c commandname


Use the "-c" option with "su" to run a command as root. See "man su".

The script below runs "whoami" three times. First as a normal user, then asks for root password, and runs "whoami" as root. And finally it runs "whoami" as the normal user again.

#!/bin/bash

whoami
su -c whoami
whoami

Call separate scripts as different users using the -c option with su:
test.sh script:
#!/bin/bash
echo "before su"
su root -c ./rootscript.sh
echo "after su"
whoami

rootscript.sh (located in the same directory hence why called by ./rootscript)
#!/bin/bash
echo "now in sub shell"
whoami
echo "exiting sub shell"

Discuss This Article

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License