📜  bash continue on error - Shell-Bash (1)

📅  最后修改于: 2023-12-03 14:39:27.508000             🧑  作者: Mango

Bash Continue on Error - Shell-Bash

When writing shell scripts, it's not uncommon to have some commands fail. However, in some cases, you may want to continue running the script even after encountering an error. This is where "continue on error" comes in. In this guide, we’ll go over how to handle errors in bash scripts and continue execution even if an error occurs.

Handling Errors in Bash Scripts

In bash scripts, you can use the set command to control how errors are handled. The most commonly used options are:

  • set -e: This option tells bash to exit immediately if any command in the script returns a non-zero exit status.
  • set +e: This option tells bash to ignore errors and continue running the script.

By default, bash scripts do not use the -e option. If a command in a script fails, the script will continue running. However, this can lead to unexpected behavior, and it's generally a good practice to use the -e option to ensure that the script stops immediately when an error occurs.

Continuing Execution After an Error

If you want to continue running a script after an error occurs, you can use the set +e command. This tells bash to ignore errors and continue running the script. However, you should be careful when using this option because it can lead to unexpected behavior.

One way to mitigate this is to use the trap command to catch the error and perform some action. For example, you can use the trap command to log the error and continue running the script:

#!/bin/bash

set -e

trap 'echo "Error: $BASH_COMMAND at line $LINENO" >> error.log' ERR

echo "Starting script"

ls /invalid/path/
echo "This line will not be executed"

echo "Script finished"

In this example, we use the set -e command to exit the script immediately if any command fails. We then use the trap command to catch the error and log it to a file called error.log. The ERR option tells bash to catch all errors.

Conclusion

In conclusion, handling errors in bash scripts is an important aspect of writing robust shell scripts. By default, bash will continue running a script even after encountering an error. However, you can use the set command to control how errors are handled, and the trap command to catch errors and perform some action before continuing execution. Remember to use these options carefully to ensure that your scripts are reliable and robust.