CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium
A junior administrator is configuring a Bash script that processes log files. The script needs to exit immediately if any command fails, to prevent further processing with potentially incorrect data. Which Bash command or construct should be used to ensure this behavior?
- A`set -u`
- B`trap 'exit 1' ERR`
- C`if ! command; then exit 1; fi`
- D`set -e`
Show answer & explanationAnswer & explanation
Correct answer: D. `set -e`
The `set -e` command (or `set -o errexit`) causes a Bash script to exit immediately if a command exits with a non-zero status, which is the standard indicator of failure. This is the most concise and common way to achieve the desired behavior across an entire script.
Why the other options are wrong
- A. `set -u` (or `set -o nounset`) causes the script to exit if an uninitialized variable is used, which is good practice but doesn't address command failures.
- B. `trap 'exit 1' ERR` is an alternative for error handling, but `set -e` is simpler and more direct for the 'exit on any command failure' requirement.
- C. This `if` statement provides explicit error checking for a single command. While effective, applying this to *every* command in a script would be verbose and less efficient than `set -e`.
Bash `set -e` (errexit)
A Bash shell option that causes the script to exit immediately if a command exits with a non-zero status, indicating failure.
- Also known as `set -o errexit`.
- Prevents script execution with potentially corrupted data after an error.
- Can be temporarily disabled with `set +e`.
- Important for robust scripting and CI/CD pipelines.
Memory trick: Set 'e' for Exit on Error, like a strict teacher stopping a bad performance.