Talk about the shell ">/dev/null 2>&1"

  
 

Today I was asked another question in one of my own technology groups, so I explained it in a common way, and made a record. Let's see if the explanation is clear!

The shell may often see: >/dev/null 2>&1

The result of the command can be defined in the form of %>

Decompose this combination: “>/dev/null 2>&1” for five parts.

1:> Represents where to redirect, for example: echo "123" > /home/123.txt2:/dev/null for empty device files 3:2> for stderr standard error 4: & means equivalent, 2>&1, indicating that 2's output redirection is equivalent to 15:1 for stdout standard output, the system default is 1, so ">/dev/null" is equivalent to " 1>/dev/null"

So, >/dev/null 2>&1 can also be written as “1> /dev/null 2> &1”

So The execution of the statement in the title of this article is: 1>/dev/null: First, the standard output is redirected to the empty device file, that is, no information is output to the terminal. To put it plainly, no information is displayed. 2>&1: Next, the standard error output is redirected to standard output because the standard output has been redirected to an empty device file, so the standard error output is also redirected to the empty device file.

Are you clear, everyone understands it!

By the way, compare the benefits of this use!

The most common ways are:

command > file 2>file with command > file 2>&1

Are there any differences?

First command > file 2>file means to send the standard output information generated by the command, and the wrong output information to file.command > file 2>file This way, stdout and stderr They are sent directly to the file, and the file will be opened twice, so that stdout and stderr will overwrite each other. This way, the FD1 and FD2 are used to grab the file at the same time. The command >file 2>&1 command sends stdout directly to file. After stderr inherits the FD1 pipeline, it is sent to file. At this time, file is only opened once, and only one pipeline is used. FD1, which includes the contents of stdout and stderr. From the IO efficiency, the efficiency of the previous command is lower than that of the latter one. Therefore, when writing a shell script, we will write command > file 2>&1 more often.

Copyright © Windows knowledge All Rights Reserved