This post explains how the shell and Unix commands handle input/output streams and how to redirect them.
Overview
“The shell and many UNIX commands take their input from standard input (stdin), write output to standard output (stdout), and write error output to standard error (stderr).”
By default, stdin connects to the keyboard while stdout and stderr display on the terminal screen. File redirection uses metacharacters to specify alternative destinations.
C Shell Family
Key redirection operators:
| Character | Action |
|---|---|
> | Redirect standard output |
>& | Redirect stdout and stderr |
! | Redirect stdout; overwrite existing file |
>&! | Redirect stdout/stderr; force overwrite |
| | | Pipe stdout to another command |
>> | Append to stdout |
>>& | Append stdout and stderr |
Example commands:
who > names— save output to file(pwd; ls -l) > out— redirect multiple commandswho >& /dev/null— suppress all output
Bourne Shell Family
Uses numeric file descriptors (0=stdin, 1=stdout, 2=stderr):
| Character | Action |
|---|---|
> | Redirect stdout |
2> | Redirect stderr |
2>&1 | Redirect stderr to stdout |
>> | Append stdout |
2>&1| | Pipe both streams |
Example commands:
who > names— redirect outputwho 2> /dev/null— suppress errors onlycat file > out 2> error— separate output and error files
Source
Reference material adapted from Math/CS at University of Picardie