How to Redirect Standard (stderr) Error in Bash
Last Updated :
08 Jan, 2024
Bash (Bourne Again SHell) is the scripting language that is generally used to automate tasks. It is a Linux shell and command language written by Brain Fox. Bash is the default shell for Linux and macOS operating systems.
What is a Standard Error in Bash?
When a code is run in Bash shell and if the code executes successfully it would return the exit code of 0. And, if the code fails or interrupts in between it would return the exit code of any non-zero positive number from 1-133.
Let's understand the exit code and error using the bash shell. It is mandatory to have a bash environment in your system for running the bash commands and scripts, if you are using Linux or macOS that's great.
Step 1. Open the terminal
Open your terminal by simply clicking on the terminal icon.
Bash shellStep 2. Exit code of successful execution of code/command
Now, we are going to write a command and then check if the exit code is 0 or Non-zero. If the script returns 0 that means the command ran successfully without any error. And, if the command returns exit code of any number between 1-133 that means the command fail to executes.
We are going to write a small script in the terminal and then check its exit code. See the image below and then we will understand it further.
Simple script to print the stringCommands used:
echo: This command is used to print something in the terminal. It is just like the print command used in Python, cout in C++, and, console.log in Javascript.
$?: This command is used to know the exit code. And this helps us to redirect the error while writing shell scripts.
$ echo "Successful script"
Output:
Successful script
The code executes successfully and hence it will return the exit code 0. To confirm it we have to run the following command:
$ echo $?
Output:
0
Yess!! the code return the exit code 0. That means the script run successfully without any error.
Step 3. Exit code while facing errors
Now, lets check the exit code if the command doesn't run successfully or face any error. For that let's write a simple and small script inside the bash terminal.
Command used:
which [package-name]: This command is useful for letting us know if the particular package is installed in our system or not. This command returns two outputs:
Output 1: If the package is installed in our system it will return the path/location, where the package has been installed.
For e.g:
$ which bash
Output:
$ /usr/bin/bash
Output 2: If the package is not installed in your system it will not print anything just the next line to write your commands.
For e.g:
$ which htop
Htop is a software available for Linux that is used for observing the state and resources that have been used by your system like RAM, ROM, CPU usage etc.
Output:
$
You can try using this command to know more and get the better understanding about this command.
Now, let's write a code to generate a error and then see what exit code it will return.
using which commandCommands used:
echo: This command is used to print something in the terminal. It is just like the print command used in Python, cout in C++, and, console.log in Javascript.
$?: This command is used to know the exit code. And this helps us to redirect the error while writing shell scripts.
which [package-name]: This command is useful for letting us know if the particular package is installed in our system or not. Read above to know more about this command.
"gfg" is not a software nor a package that can be installed in the system and since it is not installed in my system the "which" command print nothing. This shows that package is not installed in my system.
This generates error as the package is not installed in my system thus returning the exit code of "1".
NOTE: Error returns the exit code from 1-133.
Redirecting standard error in Bash
Standard error in Bash is the output thrown by the terminal that is basically a error. There are three types of standard streams that can be used by the process for input and output:
1. Standard Input - This is represented by 0. This is where program receive its input.
2. Standard Output - This is represented by 1. This is where program send its regular output.
3. Standard Error - This is represented by 2. This is useful for redirecting error messages to the logfile or anywhere else.
Look and observe the below image to understand the standard error and then we will learn how to redirect the stderr.
stderr in bashls: This command list all the contents that are in the directory.
$ ls not_exist_directory
Here we "ls" the "not_exit_directory" that is not available hence resulting in generating the error. And, when we use "echo $?" we got the exit code of "2" that is standard error and we can redirect it so we can deal with it.
There are two ways to redirect the Standard Error in Bash:
1. /dev/null :This directory is like the blackhole of the linux system. Whichever goes in here just vanish from existence. This is useful when we don't want to store the standards error.
2. Text FIles : We can create a text file and then redirect standard error in the text file so we can use and analyze it later.
Redirecting Stderr in /dev/null
Now lets redirect the standard errors in this blakhole and only get what we wanted to see that is the clean and correct output of the code/command.
$ find /etc -type f
find commandcommands used:
find: this command in linux is used to find files or to get the files that are there in the system. Here "/etc" defines that find all the files in directory name "/etc" and "-type f" represents that print the only the files not the directory.
Output:
stderr
The output also contains error while we use "find" command to display all the files present in the "/etc" directory.
Redirecting Stderr in a text file
Now we are going to redirec the error that is thrown by "find" command and then we can analyze the errors later.
$ find /etc -type f 2> errors.log
redirecting the error
Explanation:
"2> errors.log" - This statement creates a files with name "errors.log" and ">" operator will overwrite all the contents of the file with the errors that are thrown by the "find" command.
Output:
stdout
It will print all the files but without any errors as all the error are redirected to the file "errors.log".
Now let's check the "errors.log" file and see what's inside it.
Stderr in the errors.log file
As we can see all the error have been successfully redirected to the "errors.log" and now we can analyze later and thus we get the clean output of the code without getting any error. This shows how helpful redirection of standard error is. That's why it is a good practise to handle error while writing a bash script to improve its efficiency.
Conclusion
Redirection of the error while writing bash script is the important practise as bash script work is to automate tasks, hence it is important to deal with standard errors and include code that deal with the errors too. Bash language is a fascinate language to learn and work with. Linux users and those who are dealing with servers in MNCs have to work with bash to automate tasks.
Similar Reads
How to intercept all errors in a class instance ?
In this article, we will try to understand how we could easily intercept or catch all the errors in a class instance with the help of theoretical explanations as well as coding examples in JavaScript. Let us first understand the below section shows several syntaxes which we will use in order to solv
4 min read
How to Redirect Output to a File and stdout
Redirecting command output in Linux is a powerful feature that helps in logging, debugging, and managing command-line outputs efficiently. Whether you want to save the output to a file, redirect errors separately, or view the output while saving it, Linux provides various redirection operators to ac
8 min read
How to Redirect 404 errors to a page in Express.js ?
Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request metho
3 min read
How to Exit When Errors Occur in Bash Scripts
When writing Bash scripts, it's essential to include error handling to ensure that the script exits gracefully in the event of an error. In this article, we'll cover all the possible techniques for exiting when errors occur in Bash scripts, including the use of exit codes, the "set -e" option, the "
7 min read
How to remove the console errors in axios ?
In this article, we will see the âRemove the console errors in Axiosâ. The console errors method outputs an error message to the Web console. Axios is a JavaScript library that implements the Promise API that is native to JS ES6 and is used to make HTTP requests using node.js or XMLHttpRequests from
2 min read
How to enable error reporting in PHP ?
In PHP, we can decide whether to show an error to end-users or not. You can enable or disable error reporting in PHP with three approaches: Approach 1: In the php.ini file, we can set the display_error parameter as on or off. The on means errors are displayed and off means no errors to display and r
3 min read
Console.OpenStandardError Method in C#
This method is used to acquire a standard error stream. This method can be used to reacquire the standard error stream after it has been changed by the SetError method. Syntax: public static System.IO.Stream OpenStandardError (); Returns: This method returns the standard error stream. Example: The b
2 min read
How to create a Custom Error Page in Next.js ?
Creating a custom error page in Next.js allows you to provide a better user experience by customizing the appearance and messaging of error pages like 404 and 500.In this post we are going to create a custom error page or a custom 404 page in a Next JS website.What is a custom error page?The 404 pag
2 min read
How to show All Errors in PHP ?
We can show all errors in PHP using the error_reporting() function. It sets the error_reporting directive at runtime according to the level provided. If no level is provided, it will return the current error reporting level. error_reporting(E_ALL) level represents all errors, warnings, notices, etc.
3 min read
How to catch all JavaScript errors and send them to server ?
Today there are a large number of Web APIs available. One of which is GlobalEventHandlers, an OnErrorEventHandler to be called when the error is raised. The onerror property of the GlobalEventHandlers is an EventHandler that processes error events. This is great for catching exceptions that never oc
2 min read