Redirection
Redirection is sending the output of a program to somewhere other than where it would otherwise go - for example you can redirect the output of an ls command to a text file for later processing or to the grep command for filtering. Common operands include: >, >>, <, <<, and the ever popular |.
> sends output to a file (may include special files such as /dev/null) >> appends output to a file (without overwriting it) < sends output the other way << appends output the other way | sends output to a program (frequently, a system command like grep)
If you're using the bash or bourne shells, you also have some special options available to you: you can redirect standard input, standard output and standard error messages. Other shells such as csh are notably limited in redirection capability, making them better suited to interactive use than to shell programming or other complex uses.
Redirection in bash (or sh)
Bash's and sh's shining moment comes for users who need to see and/or redirect errors to somewhere other than STOUT (your console). Standard input (STIN), standard output (STOUT) and standard error (STERR) are by default sent to the same place: STOUT (on most systems, this will be your console or tty). bash labels these descriptors 0, 1 and 2, respectively -- you have 10 descriptors, but only 0-2 are actually taken by anything. So
samizdata# myprogram > file
will send the output of myprogram to file
samizdata# myprogram 2> file
will send only the error output of myprogram to file
samizdata# myprogram 2>&1 | command2
will send errors (descriptor 2,) to the same place as output (descriptor 1) and then pipe that to command2
Okay, let's say you want to send output to your screen and errors to a file. You can't just do
samizdata# myprogram 1>&2 2>&1 > errors.txt
because when you do the first switch, it's done right away and when the second >& comes around, it's getting the switched data. This is where the other, normally unused, file descriptors 3-9 come in. You can use them as place-holders, such as:
samizdata# myprogram 3>&2 2>&1 1>&3 | command
will make the output of myprogram do this: 3 point to the same place as 2, 2 point to 1, and finally, 1 point to 3 and then pipe all of it to command