Redirect Stderr to Stdout in Bash [5 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash, it’s crucial to manage both the standard output (stdout) and standard error (stderr) effectively. By default, stdout displays the regular output of a command, while stderr displays error messages. You can also redirect the stderr to stdout to capture error messages and output in the same stream or file. In this writing, I will discuss how you can redirect stderr to stdout using the Bash redirection process in different cases with some practical Bash script examples.

What Are Stdout and Stderr?

In Linux, stdout and stderr are abbreviations for standard output and standard error respectively. These are two out of three types of standard streams, standard input, output & error (represented by the file descriptors 0, 1, & 2 respectively) that Bash provides. Through them, you get to control your script, like, from where it will read input, where its output will be destined, and how it will handle error messages. Now, let’s see what stdout & stderr do:

1. Standard Output (stdout)

Stdout is the default stream where a program writes its regular output or data, that allows you to display output. By default, the output is displayed on the terminal. But you can also redirect the output to a file using the > symbol or append it to a file using the >> symbol. Moreover, you can also pipe the output of one command to another using the | symbol.

2. Standard Error (stderr)

Stderr is another default stream where a program writes its error messages or diagnostics. Unlike, stdout, stderr is typically used for error output to ensure that error messages are not mixed with regular output. Now, by default, stderr is also displayed on the terminal along with stdout. You can redirect stderr to a file also using the 2> or append using the 2>> symbol.

How to Redirect Stderr to Stdout in Bash?

To redirect stderr to stdout, you can use the redirection operator 2>&1. This will cause both stderr and stdout to be combined and then directed to the same location, let’s say terminal or to a file. For example, to redirect stderr to stdout and store them in the same file named file.txt, use the following syntax:

command > file.txt 2>&1

Note: Order of redirection is important, as it can result in different outcomes depending on where you place them. For example, if you use the syntax command 2>&1 >file.txt instead of command > file.txt 2>&1, you won’t be able to redirect stderr to the same location as stdout. Cause for the first syntax, stdout will go to the file file.txt while stderr will go to the terminal because stderr’s redirection happened before stdout’s redirection.

5 Practical Examples to Redirect Stderr to Stdout in Bash

In the following article, I will show how you can redirect error messages to command output & then store or use these output streams for further processing in different practical scenarios while generating different Bash scripts.

1. Redirect Stderr to Stdout to Store into a Single File

While working with Bash scripts, you can redirect stderr to stdout & then keep the output in a file so that both output streams are stored in a single file. You can do that by using the 2>&1 redirection operator. See the below script to see how to redirect stderr to stdout & then into a file named log.txt:

#! /bin/bash

cd /downloads > log.txt 2>&1
cat log.txt

EXPLANATION

The error messages (if any) generated by the cd command are first redirected to stdout & then both of them (stderr & stdout) are redirected to a file named log.txt using the 2>&1 operator. If log.txt already exists, it will be overwritten with the new output. Otherwise, a new fill will be created. Later, the contents of that file are displayed using the cat command.

redirect stderr to stdout to the same fileThe output & output error messages both are redirected to the log.txt file and I viewed the contents of the log.txt file using the cat command in the script.

2. Redirect Stderr to Stdout to Print in Terminal

Instead of saving the stderr to a file by redirecting it to stdout, you can also display the value just by redirecting them to the default output location, that is terminal. Check the below script to redirect stderr to stdout & then print them to the terminal screen:

#! /bin/bash

{
whoami
whoami -l
} 2>&1

EXPLANATION
In this script, the curly braces {…} are used to group the two whoami commands. Both of them are executed, and the stderr (if any) generated by them is redirected to stdout. Afterward, the stdout (along with stderr) is displayed on the terminal.

redirect stderr to stdout to display on the terminalFrom the image, you can see the redirected stdout & stderr of the commands displayed on the terminal.

3. Redirect Stderr to Stdout to Store to a variable

You can redirect stderr to stdout & then capture the combined output as a value for an assigned variable.  This process might be helpful for the situation where you may want to store the output in a variable & then use the value for some other automation. As the simplest syntax for this process, I can show you the following:

output_variable=$(command 2>&1)

Now to redirect stderr to stdout to store to a variable, check out the full bash script:

#! /bin/bash

# Function to check if a file exists
check_file_exists() {
       if [ -e "$1" ]; then
             echo "$1 exists."
       else
              echo "Error: $1 does not exist." 2>&1
       fi
}

# check if a file exists and capture the output
result=$(check_file_exists log.txt)
echo "Result: $result"

EXPLANATION
The script defines a Bash function check_file_exists that checks if a file exists and prints a message to stdout if the file exists or an error message to stderr if the file doesn’t exist. It then calls this function with the argument log.txt (the file name I want to check if it exists), which then captures the combined output in the result variable, and finally displays the content of the result variable.

bash redirect stderr to stdout to store in a variableSee from the image, that my test file log.txt exists in my Ubuntu system.

4. Redirect Stderr to Stdout to Pipe to Another Command

Sometimes you may need the output streams to be analyzed for further processing, in a more simple context, to send both of these streams as the standard input (stdin) for another command. You can do that using another popular Bash technique Piping. See the script below to redirect stderr to stdout to pipe to another command:

#! /bin/bash

{
date
date -r /var/empty/foo
} 2>&1 | grep "No such file or directory"

EXPLANATION
In this script, the curly braces {…} are used to group the two date commands. Both of them are executed, with their stderr (if any) redirected to stdout & then both of the output streams are piped to the grep command where grep searches for the line “No such file or directory”.

redirect stderr to stdout to pipe to another commandYou can see the script executes & prints the output for the grep command as both stderr & stdout were successfully piped as stdin for this command.

5. Redirect Stderr to Stdout to Discard Both of Them

Sometimes you may want to generate a bash script to automate a task where you may want the process to work in silence by just suppressing command output along with error messages.

Now the simplest and most common approach to suppress any output in Bash is by redirecting it to the null device, /dev/null. This special file in Unix-like systems discards all data written to it.

To redirect stderr to stdout to discard both of them, use the following Bash script:

#! /bin/bash

{
whoami
date
date -r /var/empty/foo
} 2>&1 > /dev/null

EXPLANATION
In this script, the entire block of commands (whoami, date, date -r /var/empty/foo) within the curly braces {…} is grouped & both stdout & stderr will be redirected (2>&1) to dev/null. This means both of the output streams will be discarded.

redirect stderr to stdout to discard both of themFrom the output image, you can see the script showing no outputs or error messages.

Conclusion

Redirecting stderr to stdout in Bash is a good practice for managing error messages and command output. It’s especially useful in scripts when you want to keep both of the data streams in the same location or both of them are needed to be analyzed for further processing. Hope through this article the concept of redirecting stderr to stdout is clear to you & also the practical examples will help you to see through the cases where you can use the technique.

People Also Ask

How Do I Ignore Errors in Bash?

To ignore errors or failures in Bash commands you can use the || operator, as it executes a command regardless of whether the previous command succeeds or fails. Moreover, you can use the set -e and set +e commands to control whether or not the script exits when an error occurs. By default, when set -e is active, the script will exit if any command returns a non-zero exit status.

How to Redirect Both Standard Output and Standard Error to the Same Location?

To redirect both the standard output (stdout) and standard error (stderr) to the same location in a Bash shell, you can use the 2>&1 operator. This will send both stdout and stderr to the same file or location. For example, command 2>&1 > file.txt.

How Do I Hide Error Output in Bash?

To hide or suppress error output (standard error) in Bash, you can redirect it to /dev/null, which is a special file that discards any data written to it. Here’s how to do it, command 2> /dev/null.

How Do I Trap Errors in Bash Scripts Linux?

To trap and handle errors you can use the trap command and custom error-handling functions in Bash scripts. The trap command allows you to specify a command or function to be executed when a certain signal or condition occurs. You can also trap or handle errors by using the exit codes, the set -e option, command substitution, and suppressing error messages.

How do I redirect a stdout to a file in Bash?

In Bash, to redirect a stdout (standard output) to a file named file.txt, you can use this syntax: command > file.txt.


Related Articles


<< Go Back to Bash RedirectionBash Redirection and Piping | Bash Scripting Tutorial

4.9/5 - (10 votes)
Monira Akter Munny

Hello!! This is Monira Akter Munny. I'm a Linux content developer executive here, at SOFTEKO company. I have completed my B.Sc. in Engineering from Rajshahi University of Engineering & Technology in the Electrical & Electronics department. I'm more of an online gaming person who also loves to read blogs & write. As an open-minded person ready to learn & adapt to new territory, I'm always excited to explore the Linux world & share it with you! Read Full Bio

Leave a Comment