OneBite.Dev - Coding blog in a bite size

What is `set -e` in shell

The `set -e` option in a shell script instructs the shell to exit immediately if any command exits with a non-zero status.

The `set -e` option in a shell script instructs the shell to exit immediately if any command exits with a non-zero status.

Command set-e `set -e` usage

You can use `set -e` at the beginning of your shell scripts to ensure that the script exits immediately if any of the commands it runs fail.

This can help to prevent errors from going unnoticed and potentially leading to more serious issues down the line.

#!/bin/bash
set - e

# The rest of your script

Good things using set-e

- **Error Detection**: Helps in detecting errors early. If any command fails, the script stops, and you get to know about the failure.

- **Safety**: Prevents subsequent commands from executing if an earlier command fails, which can sometimes prevent data loss or other issues.

Bad things using set-e

- **Control**: You lose control over error handling. You cannot run a command, check its exit status, and decide what to do next because the script exits as soon as any command fails.

- **Predictability**: It might make the script’s behavior less predictable, especially if it’s a complex script with many branching paths.

Overriding `set -e`

If you have a specific command that you expect might fail and you want to allow the script to continue executing afterward, you can use a construct like this:

command_that_might_fail || true

In this construct, if `command_that_might_fail` fails (exits with a non-zero status), the `true` command will then run, which simply exits with a zero status, allowing the script to continue.

Alternatives to `set -e`

Instead of using `set -e`, you might prefer to handle errors manually by checking the exit status of each command using `$?`, like so:

#!/bin/bash


command1
if [$ ? -ne 0]; then
    echo "command1 failed"
    exit 1
fi


command2
if [$ ? -ne 0]; then
    echo "command2 failed"
    exit 1
fi

In this script, each command is followed by a check of `$?`, which holds the exit status of the most recent command. If a command fails, a message is printed, and the script exits with a non-zero status. This approach allows for more fine-grained error handling at the cost of more verbose scripts.

bash