SoFunction
Updated on 2025-03-10

Specific use of set -e in shell

set -eis a Shell command that is used to automatically exit when the script is run. If the command execution fails, it will exit immediately and return a non-zero exit status code. This command ensures that when the script is running, if any errors occur, the script will stop running, avoiding continuing to execute commands that may cause more problems.

For example, in the following script, if an error occurs while executing the first command, the script will stop running immediately without continuing to execute the subsequent command:

#!/bin/bash
set -e

# Execute the first commandcommand1

# Execute the second commandcommand2

# Execute the third commandcommand3

In this example, ifcommand1​ If the execution fails, the script will stop running and return a non-zero exit status code. if command1​ When the execution is successful, the script will continue to be executed command2and command3

If you don't use set -e?

If not usedset -eCommand. When a command fails to execute in the script, the script will continue to execute the subsequent commands. This may cause some potential problems, as subsequent commands may continue to be executed regardless of whether the previous command was executed successfully.

For example, in the following script, if **command1​ If the execution fails, the script will continue to be executed**command2and command3

#!/bin/bash

# Execute the first commandcommand1

# Execute the second commandcommand2

# Execute the third commandcommand3

In this example, ifcommand1​​ If the execution fails, the script will continue to be executed.command2​​ andcommand3, which may lead to some potential problems.

Therefore, useset -eThe command ensures that it exits automatically when the script is running, and if the command fails to execute, it will exit immediately and return a non-zero exit status code to avoid possible problems.

How to use shell set +e, set -e

set +e When this sentence encounters a non-zero return value, it will continue to execute
After this sentence, it will exit directly if it encounters a non-zero return value.

This is the article about the specific use of set -e in shell. For more related shell set -e content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!