0
0
Bash-scriptingComparisonBeginner · 3 min read

Set -e vs Set -x vs Set -u in Bash: Key Differences and Usage

In Bash, 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.

OptionPurposeEffectCommon Use Case
set -eExit on errorStops script if any command returns non-zeroFail fast to avoid hidden errors
set -xDebuggingPrints each command before executionTrace script flow and commands
set -uUnset variable checkErrors on use of unset variablesCatch 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

bash
#!/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"
Output
mkdir: created directory '/tmp/testdir' cd /tmp/testdir bash: line 6: false: command failed
↔️

set -x Equivalent

bash
#!/bin/bash
set -x

# This script prints each command before running it
mkdir -p /tmp/testdir
cd /tmp/testdir
echo "Current directory: $(pwd)"
Output
+ mkdir -p /tmp/testdir + cd /tmp/testdir + echo 'Current directory: /tmp/testdir' Current directory: /tmp/testdir
🎯

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.
Use set -e and set -u together for safer scripts.
Use set -x temporarily during debugging to trace script execution.