Forem

Julian Toscani
Julian Toscani

Posted on • Edited on

3

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!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay