2021年9月14日

What is /dev/null 2>&1 linux file descriptor 0 1 2 for stdin, stdout and stderr In the shell, what does " 2>&1 " mean?

 

         The input stream is referred to as "standard input"; the output
       stream is referred to as "standard output"; and the error stream
       is referred to as "standard error".  These terms are abbreviated
       to form the symbols used to refer to these files, namely stdin,
       stdout, and stderr.
         On program startup, the integer file descriptors associated with
       the streams stdin, stdout, and stderr are 0, 1, and 2,
       respectively.  The preprocessor symbols STDIN_FILENO,
       STDOUT_FILENO, and STDERR_FILENO are defined with these values in
       <unistd.h>.


There are also symbolic constants defined in unistd.h for the file descriptors belonging to the standard streams stdinstdout, and stderr; see Standard Streams.

STDIN_FILENO

This macro has value 0, which is the file descriptor for standard input.

STDOUT_FILENO

This macro has value 1, which is the file descriptor for standard output.

STDERR_FILENO

This macro has value 2, which is the file descriptor for standard error output.


File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).

Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: 2>&1.

Consider >& as redirect merger operator.


Ref:

https://www.gnu.org/software/libc/manual/html_node/Descriptors-and-Streams.html

https://man7.org/linux/man-pages/man3/stdout.3.html

https://stackoverflow.com/questions/818255/in-the-shell-what-does-21-mean?noredirect=1&lq=1

沒有留言:

張貼留言

文章有誤或有問題麻煩您留言告知! 謝謝您~~