How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it? How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it? unix unix

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?


File sutest

#!/bin/bashecho "uid is ${UID}"echo "user is ${USER}"echo "username is ${USERNAME}"

run it: `./sutest' gives me

uid is 500user is stephenpusername is stephenp

but using sudo: sudo ./sutest gives

uid is 0user is rootusername is stephenp

So you retain the original user name in $USERNAME when running as sudo. This leads to a solution similar to what others posted:

#!/bin/bashsudo -u ${USERNAME} normal_command_1root_command_1root_command_2sudo -u ${USERNAME} normal_command_2# etc.

Just sudo to invoke your script in the first place, it will prompt for the password once.


I originally wrote this answer on Linux, which does have some differences with OS X

OS X (I'm testing this on Mountain Lion 10.8.3) has an environment variable SUDO_USER when you're running sudo, which can be used in place of USERNAME above, or to be more cross-platform the script could check to see if SUDO_USER is set and use it if so, or use USERNAME if that's set.

Changing the original script for OS X, it becomes...

#!/bin/bashsudo -u ${SUDO_USER} normal_command_1root_command_1root_command_2sudo -u ${SUDO_USER} normal_command_2# etc.

A first stab at making it cross-platform could be...

#!/bin/bash## set "THE_USER" to SUDO_USER if that's set,#  else set it to USERNAME if THAT is set,#   else set it to the string "unknown"# should probably then test to see if it's "unknown"#THE_USER=${SUDO_USER:-${USERNAME:-unknown}}sudo -u ${THE_USER} normal_command_1root_command_1root_command_2sudo -u ${THE_USER} normal_command_2# etc.


You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:

#!/bin/bashsudo -u username command1command2sudo -u username command3command4

When running as root, sudo doesn't ask for a password.


If you use this, check man sudo too:

#!/bin/bashsudo echo "Hi, I'm root"sudo -u nobody echo "I'm nobody"sudo -u 1000 touch /test_user