0
0
Linux CLIscripting~5 mins

Shell options (set -e, set -x) in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes scripts fail silently or it's hard to see what commands are running. Shell options like set -e and set -x help catch errors early and show commands as they run, making scripts easier to debug and safer to use.
When you want your script to stop immediately if any command fails to avoid unexpected results.
When you want to see each command printed before it runs to understand the script's flow.
When debugging a script that behaves unexpectedly and you need to trace its execution.
When running a critical automation where silent failures could cause bigger problems.
When learning shell scripting and you want clearer feedback on what your script does.
Commands
This command tells the shell to stop running the script immediately if any command returns a non-zero exit status. It helps prevent continuing after a failure.
Terminal
set -e
Expected OutputExpected
No output (command runs silently)
This command makes the shell print each command before it runs it. This helps you see exactly what the script is doing step-by-step.
Terminal
set -x
Expected OutputExpected
No output (command runs silently)
Runs a small script where set -e stops execution after the false command fails, so the echo command does not run.
Terminal
bash -c 'set -e; false; echo "This will not print"'
Expected OutputExpected
No output (command runs silently)
Runs a small script with set -x enabled, so each echo command is printed before its output.
Terminal
bash -c 'set -x; echo Hello; echo World'
Expected OutputExpected
+ echo Hello Hello + echo World World
Key Concept

If you remember nothing else from this pattern, remember: set -e stops your script on errors, and set -x shows each command as it runs.

Common Mistakes
Using set -e but not realizing some commands return non-zero codes even when successful.
The script may stop unexpectedly because some commands use non-zero exit codes for normal behavior.
Check command exit codes and handle exceptions or disable set -e temporarily around those commands.
Using set -x in a script with sensitive data without caution.
set -x prints all commands, which may expose passwords or secrets in logs.
Avoid set -x when handling secrets or disable it around sensitive commands.
Expecting set -e to catch errors in all cases, including commands in pipelines or subshells without extra care.
set -e does not always stop on errors inside pipelines or subshells by default.
Use set -o pipefail along with set -e to catch errors in pipelines.
Summary
Use set -e to make your script stop immediately on any error to avoid unexpected results.
Use set -x to print each command before it runs, helping you trace and debug your script.
Combine these options carefully to write safer and easier-to-understand shell scripts.