Shell Variable Default Values: Using ${var:-default} and ${var:=default}
Use bash parameter expansion for safe variable defaults. Learn ${var:-default}, ${var:=default}, ${var:+alt}, and ${var:?error} patterns.
Detailed Explanation
Parameter Expansion for Default Values
Bash provides parameter expansion operators that let you handle unset or empty variables gracefully. These are essential for writing robust scripts that handle missing configuration or arguments.
The Four Operators
| Syntax | Meaning |
|---|---|
${var:-default} |
Use default if var is unset or empty |
${var:=default} |
Assign default if var is unset or empty |
${var:+alternate} |
Use alternate if var IS set and non-empty |
${var:?error msg} |
Exit with error if var is unset or empty |
${var:-default} — Use Default
# Use /tmp if TMPDIR is not set
workdir="${TMPDIR:-/tmp}/myapp"
mkdir -p "$workdir"
# Default port
port="${PORT:-8080}"
echo "Listening on port $port"
${var:=default} — Assign Default
# Set and use the default
: "${LOG_LEVEL:=info}"
echo "Log level: $LOG_LEVEL"
# LOG_LEVEL is now "info" if it was previously unset
${var:?error} — Require Variable
# Exit with error if required variables are missing
: "${DATABASE_URL:?DATABASE_URL must be set}"
: "${API_KEY:?API_KEY is required}"
# Safe rm with required variable
rm -rf "${DEPLOY_DIR:?DEPLOY_DIR not set}/old_release"
${var:+alternate} — Conditional Value
# Only add --verbose flag if DEBUG is set
curl ${DEBUG:+--verbose} https://api.example.com
# Conditional configuration
docker run ${NETWORK:+--network "$NETWORK"} myimage
Without the Colon
Dropping the colon (${var-default}) only checks if the variable is
unset, not if it is empty. This is useful when empty string is a valid value.
Use Case
Configuration management scripts, Docker entrypoint scripts, CI/CD pipelines, and any script that accepts optional environment variables or command-line arguments with sensible defaults.
Try It — Shell Script Linter
Related Topics
SC2086: Unquoted Variable Expansion in Shell Scripts
Quoting
Bash Strict Mode: set -euo pipefail Explained
Script Setup
SC2115: Dangerous rm -rf with Unguarded Variables
Error Handling
SC2154: Referenced but Not Assigned Variables in Shell Scripts
ShellCheck Patterns
SC2164: cd Without Error Handling in Shell Scripts
Error Handling