What is actually /dev/null 2>&1

Lets divide the >> /dev/null 2>&1 statement into parts:
Part 1: >> output redirection
This is used to redirect the program output and append the output at the end of the file. More...
Part 2: /dev/null special file
This is a Pseudo-devices special file ls -l /dev/null will give you details of the file:
crw-rw-rw-. 1 root root 1, 3 Mar 20 18:37 /dev/null
/dev/null accepts and discards all input; produces no output (always returns an end-of-file indication on a read). source wikipedia
Part 3: 2>&1 file descriptor
Whenever you executes a program by default operating system open three files STDIN, STDOUT, and STDERR as we know whenever a file is opened the system returns a small integer called as file descriptor. The file descriptor for these files are 0, 1, 2 respectively.
So 2>&1 simply says redirect STDERR to STDOUT
& means whatever follows is a file descriptor, not a filename.
In short, by using this command you are telling your program not to shout while executing.
What is the importance of using 2>&1?
If you want to produce no output even in case of some error in the terminal. To explain lets take the following example:
$ ls -l > /dev/null
For the above command no output was printed in the terminal, but what if this command produces an error:
$ ls -l file_doesnot_exists > /dev/null 
ls: cannot access file_doesnot_exists: No such file or directory
Even though I am redirecting output to /dev/null it is getting printed into terminal. It is because we are not redirecting error output to /dev/null so in order to redirect error output as well it is required to add 2>&1
$ ls -l file_doesnot_exists > /dev/null 2>&1

Comments

Popular Posts