Set -e vs Set -x vs Set -u in Bash: Key Differences and Usage
set -e stops the script if any command fails, set -x prints each command before running it for debugging, and set -u treats unset variables as errors to prevent unexpected behavior. Each option helps improve script reliability and debugging in different ways.Quick Comparison
Here is a quick overview of what set -e, set -x, and set -u do in Bash scripts.
| Option | Purpose | Effect | Common Use Case |
|---|---|---|---|
| set -e | Exit on error | Stops script if any command returns non-zero | Fail fast to avoid hidden errors |
| set -x | Debugging | Prints each command before execution | Trace script flow and commands |
| set -u | Unset variable check | Errors on use of unset variables | Catch typos and missing variables |
Key Differences
set -e makes your script stop immediately if any command fails. This helps avoid continuing with bad data or states, making scripts safer. However, it can be tricky with commands inside conditions or loops where failure is expected.
set -x is purely for debugging. It prints each command and its arguments as they run, so you can see exactly what the script is doing step-by-step. It does not affect script logic or errors.
set -u helps catch mistakes by treating any use of an unset variable as an error. This prevents bugs caused by typos or missing environment variables. It forces you to initialize variables before use.
Code Comparison
#!/bin/bash set -e # This script stops if any command fails mkdir -p /tmp/testdir cd /tmp/testdir false # This command fails # The script will exit here, so this line won't run echo "This will not print"
set -x Equivalent
#!/bin/bash
set -x
# This script prints each command before running it
mkdir -p /tmp/testdir
cd /tmp/testdir
echo "Current directory: $(pwd)"When to Use Which
Choose set -e when you want your script to stop immediately on errors to avoid unexpected results. Use set -x when debugging to see exactly what commands run and in what order. Use set -u to catch unset variables early, preventing bugs from typos or missing inputs. Combining set -e and set -u is common for safer scripts, while set -x is usually temporary for debugging.
Key Takeaways
set -e stops the script on any command failure to prevent hidden errors.set -x prints commands as they run, helping you debug scripts step-by-step.set -u treats unset variables as errors, catching typos and missing values early.set -e and set -u together for safer scripts.set -x temporarily during debugging to trace script execution.