13.2.4 Shell redirection
Basic redirection to remember (here the [n] is an
optional number to specify the file descriptor):
[n]> file Redirect stdout (or n) to file.
[n]>> file Append stdout (or n) to file.
[n]< file Redirect stdin (or n) from file.
[n1]>&n2 Redirect stdout (or n1) to n2.
2> file >&2 Redirect stdout and stderr to file.
> file 2>&1 Redirect stdout and stderr to file.
| command Pipe stdout to command.
2>&1 | command Pipe stderr and stdout to command.
Here,
-
stdin: standard input (file descriptor = 0)
-
stdout: standard output (file descriptor = 1)
-
stderr: standard error (file descriptor = 2)
The shell allows you to open files using the exec
built-in with an
arbitrary file descriptor.
$ echo Hello >foo
$ exec 3<foo 4>bar # open files
$ cat <&3 >&4 # redirect stdin to 3, stdout to 4
$ exec 3<&- 4>&- # close files
$ cat bar
Hello
Here n<&- and
n>&- mean to close the file descriptor
n.