To check if a variable is set in Bash, use parameter expansion or conditional expressions. Below are detailed methods depending on whether you want to check if a variable exists (declared) or exists and is non-empty.
1. Check if a Variable is Set (Declared)
Method 1: Use -v
(Bash 4.2+)
Checks if the variable exists (even if empty).
if [[ -v variable_name ]]; then
echo "Variable exists."
else
echo "Variable is NOT set."
fi
Method 2: Use ${var+_}
(Works in All Bash Versions)
Expands to a dummy value (_
) if the variable is set.
if [ "${variable_name+_}" ]; then
echo "Variable exists."
else
echo "Variable is NOT set."
fi
**2. Check if a Variable is Set *and* Non-Empty**
Method 1: Use ${var:-}
Checks if the variable is non-empty.
if [ -n "${variable_name:-}" ]; then
echo "Variable is set and non-empty."
else
echo "Variable is unset or empty."
fi
Method 2: Use ${var:+_}
Expands to a dummy value (_
) only if the variable is non-empty.
if [ "${variable_name:+_}" ]; then
echo "Variable is set and non-empty."
else
echo "Variable is unset or empty."
fi
3. Check if a Positional Parameter is Set (e.g., $1
)
Use ${N:+_}
, where N
is the parameter position.
# Check if $1 (first argument) is set
if [ "${1+_}" ]; then
echo "First argument exists."
else
echo "First argument is missing."
fi
4. Edge Cases and Notes
- Empty vs. Unset:
var="" # Set but empty
unset var # Unset
[ -z "${var:-}" ] && echo "var is unset or empty"
[ -z "${var+x}" ] && echo "var is unset (even if empty)"
- Arrays:
arr=() # Declared but empty
if [[ -v arr ]]; then
echo "Array exists (even if empty)."
fi
- Environment Variables:
if [ -n "${PATH:-}" ]; then
echo "PATH is set and non-empty."
fi
Examples
Example 1: Check if a Variable is Set
name="John"
if [[ -v name ]]; then
echo "name is set."
fi
Example 2: Check if a Variable is Unset
if [ -z "${age+x}" ]; then
echo "age is unset."
fi
Example 3: Check for Non-Empty Variables in Scripts
# Check if $2 (second argument) is provided and non-empty
if [ -n "${2:-}" ]; then
echo "Second argument: $2"
else
echo "Error: Missing second argument."
exit 1
fi
Common Pitfalls
- Quoting: Always quote variables (
"${var}"
) to handle spaces/special characters. - Legacy Syntax: Avoid
[ -z "$var" ]
to check emptiness—this fails to distinguish between unset and empty variables. - Bash Version:
[[ -v var ]]
requires Bash 4.2+. Use${var+_}
for compatibility.
Summary
[[ -v var ]]
: Check if a variable is declared (Bash 4.2+).${var+_}
: Check if a variable is set (works in all versions).${var:+_}
: Check if a variable is set and non-empty.[ -n "${var:-}" ]
: Safely check for non-empty variables.
Use these methods to handle script inputs, optional parameters, and environment variables robustly!