title: How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?
body: <p>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:</p>
  
  <pre><code>#!/bin/bash
  
  command1
  sudo command2
  command3
  sudo command4
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>#!/bin/bash
  
  sleep 310
  sudo echo "Hi, I'm root"
  sleep 310
  sudo echo "I'm still root?"
  </code></pre>
  
  <p>How can I make it so that the user can just enter their password once, at the very start, and then walk away?</p>
  
  <p><em>Update:</em></p>
  
  <p>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)</p>
  
  <pre><code>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
  </code></pre>