Lesson 6.4: Redirecting input and output
The three standard streams and their numbers, writing output to files with > and >>, reading input with <, separating errors with 2>, joining them with 2>&1, throwing output away into /dev/null, and tee.
16 min
You will learn to
- Name stdin, stdout and stderr and their numbers 0, 1, 2
- Write and append to files with > and >>
- Feed a file to a command with <
- Send errors elsewhere with 2> and combine streams with 2>&1
- Discard output with /dev/null and copy it with tee
Key terms
- Standard streams
- Every program starts with three open channels: standard input (stdin, 0), standard output (stdout, 1) and standard error (stderr, 2). By default stdin is the keyboard and the other two are the terminal.
- > and >>
- > redirects stdout into a file, creating it or overwriting it; >> appends to the end.
- <
- Redirects stdin to read from a file.
- 2> and 2>&1
- 2> redirects stderr; 2>&1 sends stderr to wherever stdout currently goes. &> file is bash's shortcut for > file 2>&1.
- /dev/null
- A device that discards everything written to it and returns nothing when read.
- tee
- Copies its input to one or more files and to its output, like a T-shaped pipe fitting.
← Shell start-up files · All lessons · Pipes →