DEV Community

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️