In shell scripts, by default, there are always three files open: standard input (keyboard input), standard output (output to the screen), and standard error (also output to the screen), which correspond to file descriptors 0, 1, and 2 respectively.

  • &Is a descriptor. If 1 or 2 is not preceded by ampersand, it is treated as a normal file.
  • >Default for standard output redirection, with1 >The same
  • > 1 & 2Redirects standard output to standard error.
  • 2 > &1This means redirecting standard error output to standard output.
  • &>filenameRedirects both standard output and standard error output to filename.
  • 2 > &namely> 1 & 2That is, output the result as standard error

/dev/null is a special file that discards everything passed to it

Standard output and error output

> ls
rumenz.txt

> ls rumenz.txt 1.txt
ls: 1.txt: No such file or directory
rumenz.txt
Copy the code
  • Due to the1.txtIt doesn’t exist, sols: 1.txt: No such file or directorySo the error output is 2.
  • rumenz.txtThe files exist, sorumenz.txtThat’s standard output. Is 1.

Redirect the above stdout and error output to the file

> ls rumenz.txt 1.txt 1>out.log 2>err.log
> cat out.log
rumenz.txt
> rumenz cat err.log
ls: 1.txt: No such file or directory
Copy the code
  • out.logIt’s standard output
  • err.logError output is saved

Case analysis

> ls rumenz.txt 1.txt > out.txt
ls: 1.txt: No such file or directory
> cat out.txt
rumenz.txt
Copy the code

Since only standard output is redirected, the out.txt file only has standard output

> ls rumenz.txt 1.txt > out.log 1>&2
ls: cannot access 1.txt: No such file or directory
rumenz.txt
> cat out.log
Copy the code

> out.log redirects standard output to the file, but 1>&2 redirects standard output to error output, so there is nothing in out.log.

> ls rumenz.txt 1.txt > out.txt 2>&1
> cat out.txt 
ls: cannot access 1.txt: No such file or directory
rumenz.txt
Copy the code

> out.log redirects standard output to the file, but 2>&1 redirects error output to standard output, so out.log contains both normal and error output.

/dev/null

/dev/null: represents a black hole, usually used to discard unwanted data output or empty files for input streams

> rm -f $(find / -name rumenz) &> /dev/null
Copy the code

Original link :rumenz.com/rumenbiji/l… Wechat official account: entry station