Why is there "2>&1"

  
in the LINUX Shell?  

Often in some scripts, especially in the crontab call, the following form of command call

./t.sh >/dev/null 2>&1 first half./t.sh >/dev/null is easy to understand, so what's going on behind 2>&1?

To explain this problem, you still have to mention file redirection. We know that > and <is a file redirection. So what are 1 and 2? In the shell, each process is associated with three system files: standard input stdin, standard output stdout, and standard error stderr. The file descriptors for the three system files are 0, 1, and 2, respectively. So here 2 > & 1 means that the standard error is also output to the standard output.

The following is an example to show what effect 2>&1 has:

1234 $ cat ./t.sh#!/usr/bin/zshttttttecho "test"

t.sh contains two commands, where tttttt is a command that does not exist, and the execution will report an error. By default, the error will be output to stderr. Echo can be executed correctly and output string information to stdout. The standard output here has been redirected to /dev/null. Then standard error will also be output to /dev/null




Why 2>&1 should be written later?

First, ./t.sh >/dev/null 2>&1 redirects standard output to /dev/null, 2>&1 is the standard error copying standard output behavior That is, it is also redirected to file, the end result is that standard output and errors are redirected to file. ./t.sh 2>&1 >/dev/null The 2>&1 standard error copies the behavior of the standard output, but the standard output is still at the terminal. >/dev/null The output is redirected to /dev/null, but the standard error will still not be changed to /dev/null


The test results are as follows:

1234567891011121314 ➜ workspace ./t.sh ./t.sh:2: command not found: ttttttest➜ workspace ./t.sh >/dev/null./t.sh:2: command not found: ttttt ➜ workspace ./t.sh ./t.sh:2: command not found: ttttttest➜ workspace ./t.sh >/dev/null./t.sh:2: command not found: ttttt➜ workspace ./T.sh >/dev/null 2>&1➜ workspace ./t.sh 2>&1 /dev/null./t.sh:2: command not found: ttttttest

Copyright © Windows knowledge All Rights Reserved