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
`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`
`pair@abbey scratch$ sudo -u pair ./test2.sh `
`uid is 501`
`user is pair`
`username is pair`
`home directory is /Users/pair`
– speedarius Apr 19 '12 at 18:40