How to run shell commands in the background

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

I have already linked to some interesting shell scripts that launch Java apps. But this is the simplest way to get a Java app up and running from the command line:

Here is how you would need to execute your script/command in order to completely detach it from your session:

sh my_command.sh /dev/null 2>&1 &

Explanation: I have color-coded the command to emphasize the distinct portions of the command. The firsts part (gray) is your unmodified, naked command. The next segment (green) is redirecting standard input (‘<') to read from /dev/null (the null device). The next segment (blue) is redirecting standard output ('>‘ or ‘1>’) to /dev/null. The next segment (red) redirects standard error (‘2>’) to where standard output is being directed (‘&1’). Finally, the ampersand (‘&’) tells the shell to run the command in the background.

You are not required to read from or write to /dev/null. For instance, you will probably want to track the progress of your command by following its output, so you wouldn’t want to send it all into a black hole! Instead, just replace the second (blue) /dev/null with a filename of your choosing. [WARNING: This file will be overwritten if it already exists!!] Let’s say you choose the filename ‘my_logfile’. Now, if your program produces output as it works, you use the ‘tail’ command to check in on how your command is progressing:

tail -f my_logfile

[Just press Ctrl-c to break out of the ‘tail -f’ command.]

Post external references

  1. 1
    http://command-line.info/blog/?p=119
Source