You can use the set -e command at the beginning of your script to enable this behavior, or you can use it before individual commands to enable it only for those commands.
It’s important to note that the set -e
command only affects the exit status of individual commands. It does not catch errors caused by syntax errors or other issues in the script itself. To catch these types of errors, you can use the set -o
errexit option instead.
Let’s see a few examples:
Wrap Up
You can use the trap command to catch other signals as well, such as INT (interrupt) or TERM (terminate). For more information, you can consult the bash man page or search online for tutorials and examples.
If command1 or command2 returns a non-zero exit status, the script will exit immediately and the line echo “All commands completed successfully” will not be executed.
In this example, the || operator is used to execute the command or block of commands following it if the preceding command fails. The exit 1 command is used to exit the script with a non-zero exit status, indicating an error.
In this example, the trap command specifies that the rm -f $TEMP_FILE
command should be executed when the script receives the EXIT
signal. This ensures that the temporary file is deleted, even if the script exits due to an error.
In this example, the if statement is used to check the exit status of command1, and the case statement is used to check the output of command2.
In this example, command2 will only be executed if command1 succeeds and command3 will only be executed if command1 and command2 succeed. I hope this helps! Let me know if you have any questions.