What does 'set -e' mean in a Bash script?
set -e
is a Bash option that instructs the shell to exit immediately if any command returns a non-zero status. In other words, if any command in your script fails, the script stops rather than continuing with subsequent commands.
This behavior is useful for:
- Detecting Errors Early: By halting on the first failure, you avoid executing dependent operations that rely on a successful outcome of earlier steps.
- Safer Scripts: Helps prevent silently ignoring errors that might lead to corrupted data, incomplete installations, or misconfigurations.
Example
#!/usr/bin/env bash set -e echo "Starting script..." some_command_that_might_fail echo "If the above command fails, this line won't be executed."
- If
some_command_that_might_fail
returns a non-zero status, the script exits immediately, and you won’t see the “this line won’t be executed” message.
Cautions
- Exceptions: Certain commands like
if
statements, loops, and logical operators (||
,&&
) can override the “fail on error” behavior depending on how they’re used. - Traps or Cleanup: If you need to perform cleanup even on failure, consider using traps or conditional logic around critical sections.
Further Learning
For a deeper understanding of Unix shell scripting and better coding patterns, consider these courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews – Strengthen your algorithmic thinking, ensuring you write efficient scripts and handle edge cases gracefully.
-
Grokking the Coding Interview: Patterns for Coding Questions – Learn the most common coding patterns tested at top tech companies, boosting your problem-solving skills in both interviews and real-world development.