DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Eduardo Issao Ito
Eduardo Issao Ito

Posted on

Output redirection with bash

The command below generates output in different I/O streams: error messages should go to stderr stream and "normal" messages to stdout stream. But if you run it in a terminal both streams are written to the screen:

$ ls -d /tmp nothing
ls: cannot access 'nothing': No such file or directory
/tmp

You can redirect the output to a file. Note that the error message is written in the screen, not in in the file:

$ ls -d /tmp nothing > stdout.txt
ls: cannot access 'nothing': No such file or directory
$ cat stdout.txt
/tmp

Or you can redirect only the error message:

$ ls -d /tmp nothing 2> stderr.txt
/tmp
$ cat stderr.txt
ls: cannot access 'nothing': No such file or directory

Also, you can redirect both streams at the same time to distinct files:

$ ls -d /tmp nothing 2> stderr.txt > stdout.txt
$ cat stderr.txt 
ls: cannot access 'nothing': No such file or directory
$ cat stdout.txt 
/tmp

Or you can redirect everything to the same file:

$ ls -d /tmp nothing &> all.txt
$ cat all.txt 
ls: cannot access 'nothing': No such file or directory
/tmp

Another possibility is to redirect stderr to stdout. It can be useful when you are passing data to another command. In the example below, both lines are sent to stdout and wc will count 2 lines:

$ ls -d /tmp nothing 2>&1 | wc -l
2

Redirecting stdout to stderr is also possible. In this case both lines are sent to stderr that is displayed at the terminal screen, and nothing is sent to stdout, so wc will count 0 lines:

$ ls -d /tmp nothing 1>&2 | wc -l
0
ls: cannot access 'nothing': No such file or directory
/tmp

Top comments (1)

Collapse
 
ondrejs profile image
Ondrej

I would just add that it should work on most POSIX shells, not only for Bash.

We are hiring! Do you want to be our Senior Platform Engineer? Forem is hiring a Senior Platform Engineer

If you're interested in ops and site reliability and capable of dipping in to our Linux stack, we'd love your help shoring up our systems!