Scripting

How to Redirect Stderr to Stdout in Bash

How to Redirect Stderr to Stdout in Bash

Introduction

When sending the result of a command to a file or another command, maybe you will see error messages notifications are displayed on the screen.

In Bash and other Linux shells, there are 3 standard I/O streams. Each stream has a different numeric id:

0 – stdin: input stream.

1- stdout: output stream.

2 – stderr: error stream.

This article will show you how to redirect stderr to stdout in Bash as we go through below.

Redirecting output

Redirect is the way to know the output from one program in advance and send the result of a command to a file or another command.

The syntax:

$ command n> file

n: numeric id of stream

If the command is without n, the default will be 1- stdout.

For example, I want to send ls’s output to ls.txt file:

$ ls > ls.txt

Then I use the cat command to check the output:

$ cat ls.txt

Output:

We can combine 1- stdout with 2 – stderr:

$ command 1> file 2> file

For example:

$ ls /home 1> stdout.txt cat big.txt 2> stderr.txt

Using the cat command to check:

$ cat stdout.txt

Output:

$ cat stderr.txt

Output:

Error message because big.txt file does not exist.

Redirect stderr to stdout

The syntax:

$ command > file 2>&1

Another way:

$ command &> file

In Bash, &> is used to replace for 2>&1:

For example, I will send cat big.txt’s error to the error.txt file:

$ cat big.txt > error.txt 2>&1

Using the cat command to check:

$ cat error.txt

Output:

Conclusion

You have just seen detailed instructions on how to redirect stderr to stdout in Bash.

Thank you for reading.

Similar Posts