CS246-F20-01-UnixShell
Lecture 1.6
• IO redirection (a confusing topic!)
CS246
Input/output redirection
• Every command is associated with three standard “files”:
input (0), output (1), and error (2)
– In UNIX parlance: stdin, stdout, stderr
– In C++, these “streams”: cin, cout, cerr
– By default, these are connected to the keyboard (input) and
screen/console/shell (output & error).
$ sort -n -n means numeric sort, based on lines
7 sort reads unsorted values from stdin
30
5
5 sort prints sorted values to stdout
7
30
• Redirection allows:
– taking input from a file (faster + more accurate than typing at keyboard)
– saving output to a file (for subsequent examination or processing)
• The command is (usually) unaware of redirection!
I/O redirection I/O redirection
• Redirection performed using operators < for input and > / >>
for output to/from other sources.
– < means read input from file rather than keyboard.
– > (same as 1>), 1>, 2> means (create if needed) file and write
output/errors to file rather than screen (destructive).
– >> (same as 1>>), 1>>, 2>> means (create if needed) file and
append output/errors to file rather than screen.
$ sort –n < nums.txt
$ sort –n < nums.txt > sorted.txt
$ sort –n < nums.txt >> sorted.txt
$ sort -n < nums.txt 1> sorted.txt 2> errors.txt
End
CS246