Redirecting output from stderr to stdout

Posted by Diego Assencio on 2014.09.18 under Linux (Shell)

On Linux, some commands (e.g. strace) output relevant messages to stderr instead of stdout. This can be annoying when you try to pipe the output of a program to utilities such as less or grep. Fortunately, most modern shell interpreters allow you to redirect the output of a command on stderr to stdout (and vice-versa). Here is an example of how this can be done with bash to allow one to read the output of strace with less:

strace command 2>&1 | less

The 2>&1 part instructs the shell interpreter (in our case, bash) to redirect the contents of stderr to stdout (notice that there are no spaces in this expression). This syntax refers to the fact that in C programs, the file descriptors of stdout and stderr have values 1 and 2 respectively. To read whatever a command outputs to stderr with less, follow the recipe below:

command 2>&1 | less

NOTE: the contents originally written to stdout will still be there with the redirection above. If you really want to get only what the command originally outputs to stderr but not what it originally outputs to stdout, you must then redirect its original stdout output to somewhere else (e.g. to /dev/null):

command 2>&1 1>/dev/null | less


No comments posted yet.