When running a process, 3 things are needed. An input, an output, and an error. File descriptors for each are:
– fd 0 – input (stdin)
– fd 1 – normal output (stdinout)
– fd 2 -abnormal (stderr)
Redirection is a function that can redirect standard streams [Wikipedia]. Three operators for redirection are:
– File redirect: <, >, >>
– Pipeline: |
– File descriptor redirection: >&
FILE REDIRECT OPERATORS
Each file descriptors can be redirected to/from files: from file to fd 0 (<), from fd 1 to file (>), from fd 2 to file (2>).
PIPELINE REDIRECT OPERATOR
Consider cmd1 | cmd2. The pipe operator takes data sent to stdout by cmd1 and sends it to the input file descriptor of cmd2.
I summarized some samples of file output redirection. Probably, you could understand them better.
echo “This is a sample” > sample
— inputs “This is a sample” to sample text file
— an example of stdin
rm nofile
— outputs rm: cannot remove `nofile’: No such file or directory to screen
— an example of stderr
cat good nofile
will produce:
– this is good (stdout)
– cat: nofile: No such file or directory (stderr)
Try this! Standard file output redirection
cat good nofile > out.txt output: cat: nofile: No such file or directory cat out.txt output: this is good cat good nofile 2> err.txt output: cat: nofile: No such file or directory cat err.txt output: cat: nofile: No such file or directory
Try this! Output redirection – two at once
cat good nofile > out1.txt 2> err.txt cat out.txt output: this is good cat err.txt output: cat: nofile: No such file or directory
Try this! Redirecting stdout & stderr
cat good nofile > out-err.txt 2>&1 cat out-err.txt output: this is good cat: nofile: No such file or directory
2>&1 is called duplicating. File descriptor 2 is converted to descriptor 1. Note: duplicating is always from right to left.
> means save all file descriptor 1.
Try this! Duplicating before and after redirection
cat good nofile 2>&1 > out-err.txt cat out-error.txt output: this is good cat good nofile > out-err.txt 2>&1 cat out-err.txt output: this is good cat: nofile: No such file or directory
Try this! Piping stdout to stdin
cat good nofile | sed -n p > out.txt cat out.txt output: this is good
Try this! Piping stdout & stderr to stdin
cat good nofile 2>&1 | sed -n p > out-err.txt output: cat: nofile: No such file or directory stdin only are allowed by sed
Try this! Piping stderr to stdin
cat good nofile 2>&1 > /dev/null | sed -n p > err.txt output cat: nofile: No such file or directory