keepcalculator

06 Numbers and Powers

Bash set Command: Options, Syntax & Examples

Card No. 06·67440 · Updated · Standard formula, shown below

Average pace 5.00 min/km
Average speed
12.00 km/h
Result
Finish time
50 min
You entered
Distance
10 km
You entered
You enter
Finish time, Distance
You get
Average pace, Average speed
Rounding
2 dp

The Bash set command is a built-in shell command that controls shell behavior by setting or unsetting options and positional parameters. You use it to change how your script handles errors, unset variables, globbing, and more, making it essential for writing robust and predictable shell scripts.

What is the set Command?

The set command is a Bash built-in, meaning it is part of the shell itself rather than an external program. It serves two main purposes: setting or unsetting shell options (like -e for error exit) and assigning or displaying positional parameters (like $1, $2). It has been part of the Bourne shell since the early days of Unix and remains a fundamental tool for scripting.

When you run set with no arguments, it prints all shell variables and functions in a format that can be reused as input. But in practice, you will use it with flags to change behavior, or with -- to reset positional parameters.

Common Options and Their Meanings

Here are the most frequently used options. Each can be turned on with - and off with +. For example, set -e enables the option, set +e disables it.

  • -e (errexit): Exit immediately if a command returns a non-zero status. This is the most common option in production scripts.
  • -u (nounset): Treat unset variables as an error when expanding them, and exit immediately.
  • -x (xtrace): Print each command and its arguments to stderr before executing it. Great for debugging.
  • -o pipefail: Return the exit status of the last command in a pipeline that failed, not just the last command.
  • -f (noglob): Disable filename expansion (globbing), so * and ? are treated literally.
  • -v (verbose): Print shell input lines as they are read.
  • -n (noexec): Read commands but do not execute them. Useful for syntax checking.

How to Use set in Scripts

The typical pattern is to put set -euo pipefail at the top of a script. This combination makes scripts safer by:

  • Exiting on any error (-e)
  • Treating unset variables as errors (-u)
  • Catching errors in pipelines (-o pipefail)

For example, a script that copies a file and then deletes the source would normally continue even if the copy fails. With set -e, it stops immediately, preventing data loss.

You can also use set to change positional parameters. For instance, set -- "a" "b" sets $1 to a and $2 to b. This is handy when you need to reorder arguments or parse them with getopts.

Practical Examples

Let’s look at a few concrete examples.

Example 1: Error handling

#!/bin/bash
set -e
echo "Before error"
false
echo "After error"  # This line never runs

Without set -e, the script would print both messages. With it, it stops after false.

Example 2: Unset variable check

#!/bin/bash
set -u
echo "$UNDEFINED"  # Error: unbound variable

This exits with an error message instead of printing an empty line.

Example 3: Debugging

#!/bin/bash
set -x
x=5
echo $((x + 2))

This prints each command with a + prefix before executing, showing the variable expansion.

Common Mistakes and Pitfalls

One common mistake is using set -e in a script that calls commands that legitimately return non-zero, like grep when no match is found. In that case, the script exits unexpectedly. You can handle this by adding || true or using an if statement.

Another pitfall is forgetting that set -e does not apply to commands in an if condition or in a while loop condition, because those are expected to fail sometimes. This is by design, but it surprises many beginners.

Also, set -u can break scripts that rely on empty variables. For example, ${VAR:-default} is safe, but $VAR alone will error if unset. Always use the :- syntax when you expect a variable might be unset.

Comparison with Other Shell Options

Bash also has the shopt command, which controls additional shell options that are not available via set. For example, shopt -s nullglob makes glob patterns that match nothing expand to nothing instead of remaining literal. While set handles core POSIX options, shopt handles Bash-specific ones. Use set for portability and shopt for Bash-only features.

Another related command is readonly for making variables immutable, and export for environment variables. But set is unique in that it modifies the shell’s global behavior.

Frequently Asked Questions

What does set -e do in a Bash script?

It tells the shell to exit immediately if any command returns a non-zero exit status. This prevents the script from continuing after an error, which is usually what you want for reliability.

How do I unset an option?

Use set +e to turn off -e. The plus sign disables the option, while the minus sign enables it. For example, set +x stops debug tracing.

What is the difference between set -x and set -v?

set -x prints each command after expansion (with variables replaced by their values) to stderr. set -v prints the raw input line as it was read, before expansion. -x is more useful for debugging because it shows what is actually executed.

Does set -e work with pipelines?

By default, only the last command’s exit status matters. If you want to catch errors in any part of a pipeline, use set -o pipefail along with set -e. Then the pipeline fails if any command fails.

Can I use set to change positional parameters?

Yes, set -- arg1 arg2 sets $1 to arg1 and $2 to arg2. This is often used to reorder arguments or to reset them after a function call.

Is set -euo pipefail always recommended?

It is a good default for most scripts, but not always. Scripts that intentionally handle errors (e.g., using if to check a command’s exit status) might break. Also, set -u can cause issues with some external tools that rely on unset variables. Test your script thoroughly.

Related

Formula used
in t | Finish time | min | 50 | 0
in d | Distance | km | 10 | 0 | 100000
out pace | Average pace | min/km | t / d | 2
out speed | Average speed | km/h | d / (t / 60) | 2

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →