58

In bash, standard (1) and error (2) output can be re-routed and discarded with:

>/dev/null 2>&1

But the following example does something different:

nohup myscript.sh >myscript.log 2>&1 </dev/null &

What is the meaning/function of </dev/null in the example above? In what sort of scripting scenario would it be useful?

(Example Source)

Community
  • 1
  • 1
nmax
  • 981
  • 1
  • 11
  • 19
  • 3
    Processes can't be detached if they have any connections to the local TTY. This replaces FD 0, stdin, with a handle on `/dev/null`. – Charles Duffy Nov 13 '13 at 14:02

4 Answers4

73

</dev/null is used to avoid having the script wait for input.

Quoting from the usage of < /dev/null & in the command line:

< /dev/null is used to instantly send EOF to the program, so that it doesn't wait for input (/dev/null, the null device, is a special file that discards all data written to it, but reports that the write operation succeeded, and provides no data to any process that reads from it, yielding EOF immediately). & is a special type of command separator used to background the preceding process.

So the command:

nohup myscript.sh >myscript.log 2>&1 </dev/null &
#\__/             \___________/ \__/ \________/ ^
# |                    |          |      |      |
# |                    |          |      |  run in background
# |                    |          |      |
# |                    |          |   don't expect input
# |                    |          |   
# |                    |        redirect stderr to stdout
# |                    |           
# |                    redirect stdout to myscript.log
# |
# keep the command running 
# no matter whether the connection is lost or you logout

will move to background the command, outputting both stdout and stderr to myscript.log without waiting for any input.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
54

Redirecting /dev/null to stdin will give an immediate EOF to any read call from that process. This is typically useful to detach a process from a tty (such a process is called a daemon). For example, when starting a background process remotely over ssh, you must redirect stdin to prevent the process waiting for local input.

Another reason to redirect to /dev/null is to prevent an unused file descriptor being created for stdin. This can minimize the total open file handles when you have many long running processes.

Community
  • 1
  • 1
cmh
  • 10,612
  • 5
  • 30
  • 40
5

</dev/null provides empty input to the script...

rkh
  • 841
  • 12
  • 29
3

It is a way to close stdin, as if EOF (^D) were sent to it. It can be used as in this example with the mail command to signify it that the command should no more expect input from stdin.

It is also often used to daemonize processes (Stop 6 of the recommended approach for creating well-behaved daemons)

Community
  • 1
  • 1
damienfrancois
  • 52,978
  • 9
  • 96
  • 110