Mac OS X,  Mac OS X Server,  Mac Security,  Mass Deployment,  Ubuntu,  Unix,  VMware,  Xsan

5 Ways To Manage Background Jobs In A Shell Environment

When running commands that are going to take awhile, I frequently start them with the nohup command, disown the command from the current session or queue them for later execution. The reason is that if I’m running them from a Terminal or SSH session and the session is broken I want to make sure they complete. To schedule a job for later execution, use at. For example, if I want to perform a simple command, I can schedule it in a minute by running it as an echo piped to at:

echo "goldengirlsfix.sh" | at now + 2 minutes

Note, if using 1 minute, you’ll need that to be singular. But you can also disown the job. To do so, end a command with an & symbol. So, running a command or script that will take awhile with an ampersand at the end displays the job number for the command and then you can disown it by running disown followed by -h at the end. for example:

du -d 0 &
disown -h

If you choose not to disown the job, you can check running jobs using the jobs command at any time:

jobs

Nohup runs a command or script in the background even after a shell has been stopped:

nohup cvfsck -nv goldengirls &

The above command runs the command between nohup and the & symbol in the background. By default, you’ll then have the output to the command run in the nohup.out file in your home directory. So if your username were krypted, you could tail the output using the following command:

tail -f /Users/krypted/nohup.out

You can also use screen and then reconnect to that screen. For example, use screen with a -t to create a new screen:

screen -t sanconfigchange

Then run a command:

xsanctl sanConfigChanged

Then later, reconnect to your screen:

screen -x

And you can control-n or control-a to scroll through running background processes this way, provided each is in its own screen.

Finally, in AIX you can actually use the bg command. I used to really like this as I could basically move an existing job into the background if I’d already invoked it from a screen/session. For example, you have pid 88909 running and you want to put it into the background. You can just run bg 88909 and throw it into the background, allowing you to close a tty. But then if you’d like to look at it later, you can always pop it back using, you guessed it, fg. This only worked in AIX really, but is a great process management tool.