Coding⏱️ 2 min read📅 2026-06-03

How to Fix: Exiting a script upon encountering an error

Exit script upon error in bash scripting

Quick Answer: Use the 'exit' command after displaying the error message, or let the script fail with a non-zero exit code.

To exit a script upon encountering an error, you can use the set -e command at the beginning of your shell script. This will cause the script to terminate immediately if any command in the script returns a non-zero exit status.

💡 Example Usage:

  • Set -e at the beginning of your script:

Example Script:

  1. 1. #!/bin/bash
  2. 2. set -e
  3. 3. if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias; then
  4. Example Script (continued):

    1. 4. echo $jar_file signed successfully
    2. 5. else
    3. 6. echo ERROR: Failed to sign $jar_file. Please recheck the variables
    4. ✨ Wrapping Up

      By using set -e, you can ensure that your script terminates immediately if an error occurs, making it easier to diagnose and fix issues.

    Did this fix your problem?

    If not, try searching for specific error codes.

    🔍 Search Error Database

    ❓ Frequently Asked Questions