Cleaning up (Redirecting) output

Sometimes you cannot see the information you want because of all the error messages swamping the screen, or you want to manipulate the output in some way. So what to do? The answer is to redirect the output away from the screen to either the bit bucket or a file.

In Linux, there are three standard devices for input and output – Standard Input (STDIN), Standard Output (STDOUT), and Standard Error (STDERR). These can be referred to as 0, 1 and 2 respectively, so to redirect the output for STDERR to /dev/null (the bit bucket) you would type 2>/dev/null at the end of your command line.

For example find / -name fred 2>/dev/null results in any errors being discarded, leaving you with the list of files called fred displayed on the screen.

If you wanted to, you could redirect the output for STDERR to the same place as STDOUT by typing 2>&1. Note the & – if you don’t put that there, then the output for STDERR would be redirected to a file called 1.  By default, if you don’t name or number your redirection explicitly, then you’re talking about STDOUT, so find / -name fred > somefile.txt redirects the output for STDOUT to somefile.txt

The final alternative is to redirect the output streams to different places. For example find / -name fred >foundfiles.txt 2>/dev/null would send the list of files called fred to foundfiles.txt while discarding any errors reported by find.

You can, of course, redirect the standard output to the bit bucket and keep the errors if that’s what you really want to do!