Shell redirection in Linux

Time:2022-4-2

In the shell script, 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). Their corresponding file descriptors are 0, 1 and 2 respectively.

  • &Is a descriptor. If 1 or 2 is not preceded by &, it will be regarded as an ordinary file.
  • >The default is standard output redirection, and1>identical
  • 1>&2It means redirecting standard output to standard error
  • 2>&1This means redirecting standard error output to standard output.
  • &>filenameIt means redirecting both standard output and standard error output to the file filename
  • >&2Namely1>&2That is, output the result to the same as the standard error

/dev/nullIt’s a file. This file is special. It discards all the things 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
  • because1.txtDoesn’t exist, sols: 1.txt: No such file or directoryThe error output is 2.
  • rumenz.txtThe file exists, sorumenz.txtIs standard output. It’s 1.

Redirect the above standard output 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
  • out.logStored is standard output
  • err.logError output is stored

case analysis

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

Because only standard output is redirected, soout.txtThe file has only 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

> out.logRedirects standard output to a file, but1>&2Redirected standard output to wrong output, soout.logThere’s nothing in it

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

> out.logRedirects standard output to a file, but2>&1Redirect error output to standard output, soout.logThere are both normal and wrong outputs

/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

Original link:https://rumenz.com/rumenbiji/…
WeChat official account: entry station