DEV Community

Julian Toscani
Julian Toscani

Posted on • Edited on

TIL: Bash - Redirect Errors (stderr) to other files

Today I learned that, when redirecting output to a file in bash, you can specify where you want to redirect the stdout and stderr.

Redirecting in bash

In bash you can use > to redirect output of a command to a file. A basic example would be this:

$ echo "Hello World" > hello.txt
Enter fullscreen mode Exit fullscreen mode

This will redirect the output of the echo command to the file. As a result, it will create a hello.txt file with the content Hello World.

The cat command prints the content of a file to the terminal. Hence

$ cat foo.txt > new.txt
Enter fullscreen mode Exit fullscreen mode

will create a file called new.txt with the content of foo.txt. However, if foo.txt does not exist, it will prompt you with an error and create a file without content. Why?

$ cat foo.txt > hello.txt
$ cat: foo.txt: No such file or directory
Enter fullscreen mode Exit fullscreen mode

The reason for this is that the command differentiates between the handles stdout and stderr. Per default it only redirects stdout.

Explicitly redirecting

In order to redirect the output explicitly you have to prepend > with either 1 or 2. 1 standing for stdout and 2 for stderr. E.g.

$ cat foo.txt 1> hello.txt 2> error.txt
Enter fullscreen mode Exit fullscreen mode

This command will now redirect all stdout to hello.txt and all errors to error.txt.

As long as you are only working with one file, this might not be very helpful. However, if you loop over files in a directory it might be a different story.

If you find any mistakes or want to add something, don´t hesitate to leave a comment!

Top comments (0)