We can use the trap command to catch the error signal system by the system during script execution. Then you can execute a shell command or call a function. In this way, you can execute your custom script code on an error that occurred in a bash script.
This can be helpful to revert any partial changes, close database connections, or email status to the concerned persons, etc. You can use trap commands with `ERR` signals like:
trap 'on_error_function' ERR
When an error is generated in a shell script, it will execute a function named ‘on_error_function’ of your shell script. Instead of calling a function, you can simply run a command as well.
Example: Execute a function on Error in Bash
Let’s understand with an example. Create a sample shell script, and create a function with any name. Then add the
trap command with the function for ERR signal. Next, add a simple command that generates an error.
Execute the above script and you should see the results below:
Output:ls: cannot access '/home/tecadmin/dir_not_exists': No such file or directory Some error occurred
You can see that the error is trapped and the function
on_error() is executed by the bash script.
Example: Execute a command on Error in Bash
Let’s see one more example. Here we will execute a command when any error will occur in the shell script.
In the above script, we do not define any separate function. Simply run an echo command on error. Execute the above script and see the results.
Output:ls: cannot access '/home/tecadmin/dir_not_exists': No such file or directory Ohhh no!
Example: Get the line number of error occurred
You can also find out the line number, where the error occurred in the bash script along with the script name. To do this use the bash inbuilt ‘caller’.
Execute the above script and see the results. You will see the script name and the line number, where the error occurred.
Output:ls: cannot access '/home/tecadmin/dir_not_exists': No such file or directory Error found in: 9 ./script.sh
Thanks for reading this article. Hopefully, this tutorial helps you with better writing of shell scripts by catching the error and taking some action.
Also, remember that the ERR trap catches the runtime errors only. Like if any command returns the non-zero status code. It doesn’t catch the syntax errors, because in the case of syntax error the script fails without running any command.