Bash redirections


By default Bash opens several file descriptors: 0, 1, 2

  • 0 : standard input (stdin)

  • 1 : standard output (stdout). Buffered output.

  • 2 : standard error output (stderr). Unbuffered output.



Read input from a file: input.txt

$ my_program < input.txt


Write output to a file: out.txt

$ my_program > out.txt
$ my_program 1> out.txt


Write standard error output to a file: error.txt

$ my_program 2> error.txt


Redirect several items at once:

$ my_program <input.txt >out.txt 2>error.txt


Redirect stdout and stderr to same file: out.txt

$ my_program >out.txt 2>&1

NOTE: 2>&1 should come after >out.txt for this to work.


Usually we send general output from the program to stdout.

For errors we use stderr.

For logging purposses we also use stderr. We have the advantage for logs that stderr is not buffered, so if a signal occurs we can observe the whole log without having to flush the output like in stdout.



Reference


https://www.gnu.org/software/bash/manual/html_node/Redirections.html