When working with Bash scripts, it’s essential to know how to redirect output to different data streams, including the standard error (stderr) stream. By default, when you print or echo the output it goes to the standard output (stdout). However, you may need to echo output to stderr in some cases.
Echoing to stderr is particularly useful when your script generates an error & you want to print or echo that error message to stderr instead of stdout. So that, those error messages can be handled separately, such as being displayed or stored in a log file, etc. From this writing, you will learn different ways through which you can echo output to stderr.
How to Echo to Stderr in Bash?
To echo to stderr in Bash, you can use the >&2 redirection operator. This operator tells Bash to redirect the output of the echo command to stderr (represented by file descriptor 2). For example,
echo "Error message" >&2
Here, the echo command writes the string ‘Error message’ to the stderr.
5 Cases to Use Echo That Outputs to Stderr in Bash
Every Linux user is familiar with the fact that the echo command prints everything that you give after that to the default output stream stdout. It doesn’t even return any exit status (zero or non-zero). So, how can you use the command to send messages to stderr? Check out the following 5 ways, where I will show all the possible solutions:
1. Using ‘>&2’ Operator
The redirection operator >&2
resembles the same procedure as 1>&2
does, redirecting stdout (represented by file descriptor 1) to the stderr. Now using this simple operator you can redirect the outputs of echo commands to stderr. You can simply call a function with a message to be redirected to stderr and then run & check for the exit status of any process. If any error occurs, it will simply display that message.
See through the below Bash script for the practical overview:
#! /bin/bash
function echo_error {
message="An error occurred"
echo "$message" >&2
}
# Process that might generate error messages
cd Downloads
# Check if any error occurred
if [ $? -ne 0 ]; then
echo_error
fi
The script calls a function echo_error that sets a message & echoes it to stderr. After that, the cd command tries to change the directory to the “Downloads” directory. The if statement checks the exit status of this command using the special shell variable $?. It holds the exit status of the last executed command & compares it with the comparison operator -ne
(not equal). If the exit status is not equal to 0 (indicating an error), it calls the echo_error function to print ‘An error occurred’ to stderr.
Now, let’s run the script to see if the cd command produces an error: As you can see the command produces an error, which is redirected to stderr & displayed on the screen.
2. Using ‘printf’ Command With ‘>&2’ Operator
The printf command is used to format and print a message & >&2 redirection operator to redirect its output to stderr. By combining this command with the operator, the message will be printed to the standard error stream.
To redirect a string to stderr using the printf command with the >&2 operator, use the following Bash script:
#! /bin/bash
# echo the message to stderr
printf "An error occurred!\n" >&2
The script uses the printf
command to print a message followed by a newline character \n
to the standard error stream using the redirection operator >&2
.
Now, let’s run the script to print the string: The message is simply redirected to stderr & being displayed.
3. Using ‘logger -s’ Command
The logger command is used in Unix-like operating systems to send a message to the system logs (/var/log/syslog). By default, it sends the logs to the facility named as a user with priority named as notice (i.e., user.notice). However, using the -s
option of this command you can send a log message to the system log as well as display it on the console (stderr).
Let’s explore the following bash script to use the logger command to send messages to stderr:
#! /bin/bash
function echo_to_stderr {
#echo the message to stderr using the logger command
logger -s "$1"
# check if the script succeeded
if [ $? -ne 0 ]; then
echo "An error occurred" >&2
fi
}
echo_to_stderr "An error occurred"
In the script, the echo_to_stderr function logs the provided message to stderr using the logger -s
command. After that, the if-else block checks for the exit status (same as before) of the command and echoes the string based on the exit status value.
From the output, you can see the log info, stored by the logger command along with the message that was redirected to stderr.
4. Using ‘/dev/stderr’
Another way to redirect output to the stderr is by using the special file /dev/stderr that represents the stderr stream. This special device allows users to explicitly send output to the error stream.
NOTE: While /dev/stderr
is a common convention in Unix-like OSs, it may not work on all systems or in all shell environments. Besides, if you need your code to be highly portable & compatible, you might want to consider using the >&2
redirection operator.
To redirect the output of echo to stderr using the /dev/stderr device path, use the following Bash script:
#! /bin/bash
log_error() {
local message="$1"
echo "Error: $message" >/dev/stderr
}
log_error "An error occurred"
The script defines a function log_error
, that takes one argument, message, which is the error message to be logged. Inside the function, the message is printed to the stderr stream using the echo command. The > /dev/stderr
redirection is used to ensure that the string is sent to stderr. After defining the function, it is called with the message An error occurred.
The error message is sent to stderr & displayed to the terminal.
5. Using ‘/proc/self/fd/2’
In the Unix-line operating system, ‘/proc/self/fd/2’ is a special path that allows you to access and manipulate file descriptors. In particular, the path refers to the file descriptor 2 of the current process.
Here, /proc is a virtual file system (not an actual directory on disk) that provides information about running processes and their resources. self is a symbolic link to the process’s own directory within /proc. Whereas, fd stands for file descriptor & 2 represents file descriptor 2 that is used for standard error (stderr).
Now, use the /proc/self/fd/2
path in a Bash script to redirect the output of echo or any other command to stderr. Here’s how you can do that:
#! /bin/bash
echo "This is an error message!" > /proc/self/fd/2
Now, let’s run the script:
The error message is sent to stderr & displayed to the terminal.
Conclusion
To sum up, echoing messages to stderr instead of the default stream stdout is a simple and effective way to handle error messages. In this writing, I tried to provide a clear understanding of stderr, and how to echo output to stderr with practical bash script examples. Hope this writing helps!
People Also Ask
What is Stderr?
Stderr is a data stream (represented by file descriptor ‘2’) that is used to output error messages. By default, stderr is written to stderr, but it can also be redirected to files or other devices.
Does Echo Go to Stdout?
Yes. By default, the echo command in Unix-like operating systems sends its output to the standard output (stdout). This means that any text or message you provide as an argument to echo will be displayed on the terminal.
Why Echo to Stderr?
There are several reasons why you might want to echo to stderr. For example, to log error messages to file for later review, display error messages in the terminal or send them to another program for further processing.
How Do I Redirect Errors in Bash?
In Bash, you can redirect error messages (stderr) to the terminal, to a file, or even discard them by redirecting to the null device ‘/dev/null’ using the redirection operator 2>
. To redirect errors to a file, use command syntax, command 2> log.txt
, and to discard them, use command syntax, command 2> /dev/null
.
What is the Difference Between 2 >/Dev/Null and 2 >&1?
The key difference is that 2> /dev/null
redirects the standard error (stderr) to /dev/null, which is a special device file that discards all data written to it. Whereas 2>&1
, redirects stderr to the same location as the standard output (stdout). It combines both stdout & stderr into a single stream, which is often useful when you need them to be on the same destination.
Related Articles
- How to Read From Stdin in Bash? [4 Cases With Examples]
- Bash Input Redirection [3 Practical Cases]
- What is Output Redirection in Bash [With 4 Practical Cases]
- How to Redirect Stderr in Bash [5 Practical Cases]
- How to Redirect Stdout and Stderr to File in Bash [5 Cases]
- Redirect Stderr to Stdout in Bash [5 Examples]
<< Go Back to Bash Redirection | Bash Redirection and Piping | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners