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

I want to write a shell script to automate a series of commands. The problem is some commands MUST be run as superuser and some commands MUST NOT be run as superuser. What I have done so far is something like this:

#!/bin/bash

command1
sudo command2
command3
sudo command4

The problem is, this means somebody has to wait until command1 finishes before they are prompted for a password, then, if command3 takes long enough, they will then have to wait for command3 to finish. It would be nice if the person could get up and walk away, then come back an hour later and be done. For example, the following script has this problem:

#!/bin/bash

sleep 310
sudo echo "Hi, I'm root"
sleep 310
sudo echo "I'm still root?"

How can I make it so that the user can just enter their password once, at the very start, and then walk away?

Update:

Thanks for the responses. I'm running on Mac OS X Lion and ran Stephen P's script and got different results: (I also added $HOME)

pair@abbey scratch$ ./test2.sh
uid is 501
user is pair
username is 
home directory is /Users/pair
pair@abbey scratch$ sudo ./test2.sh 
Password:
uid is 0
user is root
username is root
home directory is /Users/pair

This question is related to unix sudo

The answer is


Well, you have some options.

You could configure sudo to not prompt for a password. This is not recommended, due to the security risks.

You could write an expect script to read the password and supply it to sudo when required, but that's clunky and fragile.

I would recommend designing the script to run as root and drop its privileges whenever they're not needed. Simply have it sudo -u someotheruser command for the commands that don't require root.

(If they have to run specifically as the user invoking the script, then you could have the script save the uid and invoke a second script via sudo with the id as an argument, so it knows who to su to..)


If you use this, check man sudo too:

#!/bin/bash

sudo echo "Hi, I'm root"

sudo -u nobody echo "I'm nobody"

sudo -u 1000 touch /test_user

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

#!/bin/bash

sudo -u username command1
command2
sudo -u username command3
command4

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