How to Redirect Stderr in Bash [5 Practical Cases]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Learning how to redirect stderr (standard error) is a must-know knowledge for every Linux or Unix system administrator or developer while Bash scripting. Cause, it makes it simpler to debug, log, and monitor your Bash scripts and programs since it lets you manage error messages separately from stdout (standard output). This writing will cover the basics of stderr redirection & how you can redirect stderr with some practical Bash script examples.

Key Takeaways

  • Learning the concept of the stderr redirection process.
  • Getting to learn how to redirect stderr with practical cases.

Free Downloads

What is Stderr?

‘Stderr’ stands for ‘standard error’. It is one of the three standard I/O (input/output) streams used by programs in Unix-like operating systems, including Linux. This is the stream through which a program sends error messages. By default, it sends data to the terminal just like stdout (standard output). However, it lets programs separate regular output from error messages too. With the help of the redirection process, it can be redirected to a log file, discarded, or even sent to a variable for further processing.

5 Practical Cases to Redirect Stderr in Bash

In the following article, I will show 5 practical cases of how you can redirect stderr (error messages) generated by different command-line tools while creating Bash scripts.

Case 1: Redirecting Stderr to a File in Bash

In Bash, you can redirect Stderr to a file using the ‘2>’ redirection operator. Follow the below steps to see how I used the redirection process while generating a Bash script:

Steps to Follow >

❶ At first, open your Ubuntu Terminal application.

❷ Now, open a file, let’s say, named ‘file.sh’ in the nano editor by using the following command:

nano file.sh

➌ Next, write the following script inside the Bash file in the nano text editor:

#! /bin/bash

cd /nonexistent_directory 2> log.txt
cat log.txt

EXPLANATION
In 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 of the cd command are redirected to a file named ‘log.txt’ using the ‘2>’ operator. If ‘log.txt’ already exists, it will be overwritten with the new output. Otherwise, a new fill will be created. Finally, through the script’s last line, the contents of that file will be 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 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.
  • file.sh: File which you want to make executable.

➏ Finally, run the script by the following command:

./file.sh

Redirect stderr in a file in bashFrom the image, you can see that stderr messages are redirected to the ‘log.txt’ file and I viewed the contents of the ‘log.txt’ file using the cat command in the script.

Case 2: Appending Stderr to a File in Bash

Normally, when you redirect stderr to a file with the ‘2>’ redirection operator, it overwrites the file. But if you want, you can append the stderr to the existing file contents while redirecting by using the ‘2>>’ redirection operators. Check out the following script:

You can follow the Steps of Case 01, to see how to save,  make the script executable, and run it.

Script (append.sh) >

#! /bin/bash

whoami -l 2>> log.txt

EXPLANATION
In this script, the stderr of thewhoami command is appended to a file named ‘log.txt’ using the ‘2>>’ operator. It writes inside the ‘log.txt’ file, generally at the bottom of the previously stored content (if any) of the file.

Append stderr in a fileSee from the output image, the stderr messages are appended to the ‘log.txt’ file and I viewed the contents of the ‘log.txt’ file using the cat command in the script. Where the new message is stored at the bottom of the previous file content.

Case 3: Redirecting Stderr to “/dev/null” in Bash

A common technique in Unix-like systems is redirecting stderr to ‘/dev/null’ when you want to discard error messages or prevent them from cluttering your terminal or log files.

The null device, ‘/dev/null’ is a special file in Unix-like systems that discards all data written to it.

You can follow the Steps of Case 01, to see how to save,  make the script executable, and run it.

Script (null.sh) >

#! /bin/bash

{
date  # Display the current date & time
date -r /var/empty/foo # Attempt to display the modification timestamp of a non-existent file
} 2> /dev/null

EXPLANATION
In this script, the curly braces ‘{…}’ are used to group the two date commands. Both of them are executed, with their stdout displayed on the terminal. But the ‘2> /dev/null’ part ensures that any error messages (stderr) generated by either of the date commands will be redirected to the null device file. This effectively silences/discards error messages.

Discarding stderr in bashOnly the stdout of the executed commands of the script is displayed, while stderr is discarded.

Case 4: Redirecting Stderr to a Variable in Bash

You can redirect stderr to a variable in a Bash script, for that you can use command substitution along with the ‘2>&1’ redirection operator. Go through the following script for further clarification:

You can follow the Steps of Case 01, to see how to save,  make the script executable, and run it.

Script (var.sh) >

#! /bin/bash

# Prompt the user for a command
read -p "Enter a Command:  " user_command

# Run the user-entered command and store both stdout & stderr
result=$(eval "$user_command" 2>&1)

# Check whether an error occurred or not

if [ $? -ne 0 ]; then
    error_message="$result"
    echo "$error_message"
else
    echo "Executed successfully."
fi

EXPLANATION
The script prompts the user to enter a command using ‘read -p’. After the user enters, it is stored in the ‘user_command’ variable. Later the eval command is used to execute that command & ‘2>&1’ is used to redirect both stdout & stderr in the ‘result’ variable.

After that, the script checks the exit status of the executed command using ‘$?’. If the exit status is non-zero, it indicates an error occurred & user inserted a wrong command. Then the content of the ‘result’ variable is assigned to the ‘error_message’ variable, and an error message is displayed. Otherwise, a success message is displayed.

Redirect stderr to a variable in bashI ran the script twice so that you can see the difference between the outputs. At first, I entered a valid command ‘date’. So it was executed successfully. But the second time, I entered the date command with option -r to view the modification timestamp of a non-existent file /var/empty/foo. As a result, the script outputs the error message.

Case 5: Redirecting Stderr to Stdout in Bash

One quite common scenario while Bash scripting is to redirect stderr to stdout while storing a program’s output to a file. That way you can have everything in one file.

You can follow the Steps of Case 01, to see how to save,  make the script executable, and run it.

Script (to_stdout.sh) >

#! /bin/bash

{
whoami
whoami -l
} > output.txt 2>&1

echo "The output is '$(cat output.txt)'"
EXPLANATION
  In this script, the curly braces ‘{…}’ are used to group the two whoami commands. Both of them are executed & ‘> output.txt’ part redirects the stdout of these commands to the ‘output.txt’ file, and ‘2>&1’ redirects the stderr to the current location of stdout, that is ‘output.txt’. Later the content of the output.txt file is displayed using the cat command.

Redirect stderr to stdout in bashFrom the image, you can see the stderr is redirected to the same location stdout is, that is the output.txt file. And, inside the file, notice the stdout & stderr of the executed commands.

Importance of Redirecting Stderr in Bash

Redirecting stderr (standard error) in Bash is important for several reasons:

  • Error Handling → Allows you to separate error messages so that you can handle errors more effectively.
  • Logging → While automating, redirecting stderr to a log file helps to make it easier to diagnose issues.
  • Cleaner Terminal → It’s an essential process for those times when you want to keep your terminal clean & only want to display outputs. You can just redirect error messages to the null device to be discarded.
  • Data Integrity → When processing important data, having a clean separation between regular data and error messages ensures data integrity.
  • Troubleshooting → Handling error messages separately helps in troubleshooting and improving the script.

Conclusion

To sum up, whether you want to store, append, display, or discard the Stdout and Stderr of commands, the Bash redirection process helps to manage them. The discussed practical cases in this article should help you to learn how to handle them. Happy Bash scripting!

People Also Ask

What does 2 >& 1 do in Bash?

In Bash, ‘2>&1’ is a special syntax used for redirecting the standard error (represented by file descriptor ‘2’) to the same location as the standard output (represented by file descriptor ‘1’). You can do that using the command syntax, ‘command > file_name 2>&1’.

What is the meaning of >&2 in Bash?

The redirection syntax ‘>&2’ is used to send the output to the standard error (stderr) stream, which is denoted by file descriptor ‘2’.

What is redirect to Dev Null 2 >& 1?

In Bash, ‘2>&1’ is a special syntax used for redirecting the standard error (represented by file descriptor ‘2’) to the same location as the standard output (represented by file descriptor ‘1’). When you are redirecting to ‘/dev/null’ a special device file that discards any data written to it, it means you are suppressing both output & error.

What does 2 >& 1 at the end of a command do?

When you use ‘2>&1’ at the end of the command it means that both the standard error (represented by file descriptor ‘2’) & the standard output (represented by file descriptor ‘1’) will be redirected to the same location.

Related Articles


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

5/5 - (1 vote)
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