Redirection is the shell syntax for attaching a process's file descriptors to files rather than the terminal. The basic operators are:
command > file # stdout to file (truncate)
command >> file # stdout to file (append)
command < file # stdin from file
command 2> file # stderr to file
command 2>&1 # stderr to wherever stdout points now
command &> file # stdout and stderr (bash only)
command <<< "text" # here-string: stdin from text
command <<EOF # here-doc: stdin from inline text
multi-line content
EOF
Redirections are processed left to right. >file 2>&1 first sends stdout to the file, then points stderr at the same place. 2>&1 >file sends stderr wherever stdout originally pointed (the terminal) and then changes stdout to the file—almost always not what you want.
Non-standard descriptors can also be redirected: 3> file opens fd 3 on a file, which a program can then write to. This is the trick behind patterns like exec 3<&0 to save stdin before manipulating it. Combined with pipes and subshells, redirection is what gives the shell its almost-programming-language power.
Related terms: Pipe, stdin, stdout, stderr, Here Document
Discussed in:
- Chapter 7: Pipes, Redirection, and Streams — Input Redirection
Also defined in: Textbook of Linux