0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use set -u in Bash to Catch Unset Variables

Use set -u in bash scripts to make the shell treat unset variables as errors. This helps catch typos or missing variables by stopping the script with an error message when an unset variable is used.
📐

Syntax

The command set -u enables a shell option that treats unset variables as errors. When this option is active, any attempt to use a variable that has not been set will cause the script to exit with an error.

You can disable this behavior with set +u.

bash
set -u

# Your script commands here

set +u
💻

Example

This example shows how set -u stops the script when an unset variable is used, helping you catch mistakes early.

bash
#!/bin/bash
set -u

name="Alice"
echo "Hello, $name!"
echo "Your age is $age"  # 'age' is not set, will cause error
Output
./script.sh: line 6: age: unbound variable
⚠️

Common Pitfalls

Using set -u can cause scripts to fail unexpectedly if you try to use variables that might not be set. To avoid this, always initialize variables or check if they are set before use.

For example, use parameter expansion with a default value to prevent errors:

bash
# Wrong way (causes error with set -u)
echo "$username"

# Right way (provides default if unset)
echo "${username:-guest}"
Output
guest
📊

Quick Reference

  • set -u: Treat unset variables as errors.
  • set +u: Disable this behavior.
  • Use ${var:-default} to provide defaults for possibly unset variables.
  • Helps catch typos and missing variables early in scripts.

Key Takeaways

Use set -u to catch unset variables and avoid silent errors in bash scripts.
Always initialize variables or use default values to prevent script failures with set -u.
Disable with set +u if you need to allow unset variables temporarily.
Parameter expansion like ${var:-default} helps safely handle unset variables.
Using set -u improves script reliability by catching mistakes early.