Bash

Default Value for Unset Variable

admin by @admin ADMIN
Jun 14, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Three parameter-expansion idioms for "use this if the variable is empty / unset". Replaces the verbose `if [[ -z "$VAR" ]]; then VAR=default; fi` everywhere.
Bash
Raw
# ${var:-default}  : use default if var is unset OR empty (most common)
echo "${USER:-anonymous}"

# ${var:=default}  : same, but ALSO assigns to var
echo "${COUNT:=0}"; echo "$COUNT"   # 0  0

# ${var:?error}    : exit with error if var is unset/empty (defensive)
: "${API_KEY:?Need to set API_KEY in environment}"
# bash: API_KEY: Need to set API_KEY in environment

# ${var:+alt}      : use alt if var IS set, otherwise nothing
echo "logged in as ${USER:+$USER}"

# Distinguish "unset" from "empty"
# ${var-default}   : default ONLY if unset
# ${var:-default}  : default if unset OR empty
unset X;   echo "${X-default}"     # default
X="";      echo "${X-default}"     # (empty)
X="";      echo "${X:-default}"    # default
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.