Facebook Twitter Instagram
    TecAdmin
    • Home
    • Ubuntu 20.04
      • Upgrade Ubuntu
      • Install Java
      • Install Node.js
      • Install Docker
      • Install LAMP Stack
    • Tutorials
      • AWS
      • Shell Scripting
      • Docker
      • Git
      • MongoDB
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    Home»Programming»Bash Shell»How to run a command or function on error in Bash Script

    How to run a command or function on error in Bash Script

    RahulBy RahulJuly 30, 20223 Mins ReadUpdated:July 30, 2022

    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 command with ERR signal 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.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/usr/bin/env bash
     
    on_error(){
      echo "Some error occurred"
    }
     
    trap 'on_error' ERR
     
    ls ~/dir_not_exists

    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.

    1
    2
    3
    4
    5
    #!/usr/bin/env bash
     
    trap 'echo Ohhh no!' ERR
     
    ls ~/dir_not_exists

    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’.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/usr/bin/env bash
     
    on_error(){
            echo "Error found in: $(caller)" >&2
    }
     
    trap 'on_error' ERR
     
    ls ~/dir_not_exists

    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

    Conclusion

    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.

    bash error shell script trap
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp
    Previous ArticleHow to list all collections in MongoDB database
    Next Article (Resolved) Unknown collation: utf8mb4_unicode_520_ci

    Related Posts

    How to Correctly Set the $PATH variable in Bash

    2 Mins Read

    How to run a command on bash script exits

    1 Min Read

    Convert String to Lowercase in Bash – Easier Than You Think

    Updated:August 1, 20221 Min Read

    Check if a script is running as root user in Linux

    2 Mins Read

    How to declare boolean variable in shell script

    Updated:July 25, 20221 Min Read

    GPG Key Error during MySQL 5.7 Installation

    Updated:July 18, 20221 Min Read

    Leave A Reply Cancel Reply

    Recent Posts
    • How to Import GPG Keys on Ubuntu & Debian (without apt-key)
    • How To Install Google Chrome On macOS
    • How to Install Minecraft on Ubuntu 22.04 & 20.04
    • Running a Cron job every Sunday (Weekly)
    • Running Multiple Commands At Once in Linux
    Facebook Twitter Instagram Pinterest
    © 2022 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.