3

from http://www.gnu.org/software/coreutils/manual/html_node/nohup-invocation.html

nohup runs the given command with hangup signals ignored, so that the command can continue running in the background after you log out.

Synopsis: nohup command [arg]...

If standard input is a terminal, redirect it so that terminal sessions do not mistakenly consider the terminal to be used by the command.

  1. Why do we need to do this:

    Make the substitute file descriptor unreadable, so that commands that mistakenly attempt to read from standard input can report an error.

  2. Isn't redirection stdin from a file done by nohup command [arg]... 0<myfile? why 0>/dev/null?

    This redirection is a GNU extension; programs intended to be portable to non-GNU hosts can use nohup command [arg]... 0>/dev/null instead.

0

1 Answer 1

2

Imagine you are trying to run a complex script with nohup. You can detect if it tries to read stdin by redirecting stdin to a file descriptor that cannot be read from. Look at these two examples: first 0</dev/null:

rm nohup.out
nohup sh -c 'head -1' 0</dev/null
echo $?
cat nohup.out 

The nohup.out file is empty, and the return code ($?) from the script is 0 ie ok, as the script just read end-of-file. Now try the same script with 0>/dev/null ie 0 opened for output only:

rm nohup.out
nohup sh -c 'head -1' 0>/dev/null
echo $?
cat nohup.out 

This gives the error message in nohup.out of

head: error reading 'standard input': Bad file descriptor

and the exit code is 1, fail. This is presumably more useful to you. You can also get the same effect by closing stdin with 0<&-:

rm nohup.out
nohup sh -c 'head -1' 0<&-
echo $?
cat nohup.out 
4
  • Thanks. I can't figure out if your reply answeres any of my two questions.
    – Tim
    Commented Feb 28, 2016 at 17:16
  • The redirection of stdin for nohup is entirely optional as nohup will usually redirect it to </dev/null if it was a terminal, to avoid the terminal not being able to close when you type exit. You can do your own 0< redirection, to /dev/null or a file, to avoid this. If you don't expect your command to read stdin you can detect if it does by forcing such reads to return an error instead of end-of-file. You do this by opening stdin for writes only (0>) instead of the usual reads only (0<). It's still just optional, to help debug any problems, i.e. "good practice".
    – meuh
    Commented Feb 28, 2016 at 18:13
  • thanks. " This is presumably more useful to you." Do you mean exit code 1 is more useful than exit code 0?
    – Tim
    Commented Mar 1, 2016 at 4:56
  • Yes, it is easy in a shell script to test if a command failed with an exit other than zero (eg you can just do if ! command; then ... fi), and this is simpler than looking for error messages.
    – meuh
    Commented Mar 1, 2016 at 13:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .