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.
Download the Practice Bash Script Files:
What Are Stdout and Stderr?
Linux provides three types of standard streams, standard input, output & error (represented by the file descriptors ‘0’, ‘1’, & ‘2’ respectively). 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)
Bash allows you to display output using standard output (stdout). 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)
In addition to stdout, bash also provides a separate stream called standard error for handling error messages & diagnostic output. By default, stderr is 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
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 & store them to the same file named ‘file.txt’,
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 of 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.
Example 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. Follow the below steps to see how I redirected stderr to stdout & then into a file named log.txt:
-
First, open your Ubuntu Terminal application.
-
Now, open a file, let’s say, named ‘same_file.sh’ in the nano editor by using the following command:
nano same_file.sh
-
Next, write the following script inside the Bash file in the nano text editor:
#! /bin/bash cd /downloads > log.txt 2>&1 cat log.txt
EXPLANATIONIn the script’s first line, ‘#!’ is shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s Bash situated in the /bin directory. In the next line, 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’.
-
Then, press CTRL+S to save the file & press CTRL+X to exit the nano editor.
-
After that, use the following command to make the script executable:
chmod u+x same_file.sh
explanation- chmod: Changes the permission of files and directories.
- u+x: Argument with chmod command to add the executable permission for the user.
- same_file.sh: File which you want to make executable.
-
Finally, run the script by the following command:
./same_file.sh
The 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.
Example 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 where I will redirect stderr to stdout & then print them to the terminal screen:
You can follow the Steps of Example 1, to see how to save, make the script executable, and run it.
Script (terminal.sh) >
#! /bin/bash
{
whoami
whoami -l
} 2>&1
From the image, you can see the redirected stdout & stderr of the commands displayed on the terminal.
Example 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)
Check out the following script for a more practical approach to the case:
You can follow the Steps of Example 1, to see how to save, make the script executable, and run it.
Script (variable.sh) >
#! /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"
See from the image, that my test file ‘log.txt’ exists in my Ubuntu system.
Example 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 for a practical approach:
You can follow the Steps of Example 1, to see how to save, make the script executable, and run it.
Script (pipe.sh) >
#! /bin/bash
{
date
date -r /var/empty/foo
} 2>&1 | grep "No such file or directory"
You can see the script executes & prints the output for the grep command as both stderr & stdout were successfully piped as stdin for this command.
Example 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.
You can follow the Steps of Example 1, to see how to save, make the script executable, and run it.
Script (null.sh) >
#! /bin/bash
{
whoami
date
date -r /var/empty/foo
} 2>&1 > /dev/null
From 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?
In Bash, you can ignore errors or failures in commands using several methods. For example, you can use the ‘||’ operator, as it executes a command regardless of whether the previous command succeeds or fails. Also, 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?
You can trap and handle errors using 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.