Input/output redirection and piping


In addition to basic argument processing, shell command lines may include special syntax for changing the default input and output of a command. Most UNIX commands by default read from a "standard input" (file descriptor, abbreviated fd 0) and write to a "standard output" (fd 1); they may also write error messages or other exceptional output to a "standard error" (fd 2) channel. By default these are all connected to the terminal.

Redirecting input
sort <filename

< redirects standard input to read from the indicated filename.

Redirecting output
grep syslog /etc/init.d/* >filename

> redirects standard output to write to an indicated filename. You may also see 2>filename which redirects standard output (fd 2), or a construct like 2>&1 which means "duplicate fd 1 onto fd 2", which makes standard output and standard error go to the same place. >> appends output to a file rather than overwriting it.

Piping
grep Smith addresslist | sort | uniq

A pipeline | between commands directs the standard output of the command on the left to the standard input of the command on the right (without using a temporary file); this allows commands to process each other's output. Any number of processes can be chained into a pipeline to sequentially process data.

Next ->


Steve VanDevender
Last modified: Tue Jul 6 14:28:25 PDT 2004