Default Values with Parameter Expansion

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 45 of 205

A parameter expansion is any place where Bash replaces $name or ${name} with a value. The braced form can do more than just insert a value: it can supply a fallback when the variable is missing, assign one, require that the variable exists, or substitute something else when it does. These forms let a script cope with missing input without writing a separate if statement every time.

Three States of a Variable

To understand the operators, first separate the situations in which a variable can be:

StateExampleMeaning
Unsetunset nameThe name does not exist
Empty (null)name=""The name exists and holds an empty string
Set and non-emptyname=AnaThe name holds a value

Each of the operators below comes in two forms. With a colon (:-) the test is "unset or empty". Without the colon (-) the test is only "unset".

The Operators at a Glance

ExpansionIf the variable is unsetIf emptyIf non-empty
${var:-word}wordwordvalue
${var-word}wordemptyvalue
${var:=word}assigns word, gives wordassigns word, gives wordvalue
${var=word}assigns word, gives wordemptyvalue
${var:?message}prints message, stopsprints message, stopsvalue
${var?message}prints message, stopsemptyvalue
${var:+word}emptyemptyword
${var+word}emptywordword

The script below prints all four basic results (-, :-, +, :+) for a variable in each state. It uses ${!name}, which reads the variable whose name is stored in name, so one loop can handle all three variables:

cat > d1.sh <<'EOF'
unset unsetv
emptyv=""
filled=hello
for name in unsetv emptyv filled; do
  echo "== $name"
  echo "  \${$name-fallback}  -> [${!name-fallback}]"
  echo "  \${$name:-fallback} -> [${!name:-fallback}]"
  echo "  \${$name+alt}       -> [${!name+alt}]"
  echo "  \${$name:+alt}      -> [${!name:+alt}]"
done
EOF
bash d1.sh
== unsetv
  ${unsetv-fallback}  -> [fallback]
  ${unsetv:-fallback} -> [fallback]
  ${unsetv+alt}       -> []
  ${unsetv:+alt}      -> []
== emptyv
  ${emptyv-fallback}  -> []
  ${emptyv:-fallback} -> [fallback]
  ${emptyv+alt}       -> [alt]
  ${emptyv:+alt}      -> []
== filled
  ${filled-fallback}  -> [hello]
  ${filled:-fallback} -> [hello]
  ${filled+alt}       -> [alt]
  ${filled:+alt}      -> [alt]

The only differences between the colon and non-colon forms appear in the middle block, for the empty variable. In everyday scripts the colon forms are usually what you want, because an empty value is rarely a useful value.

Using a Default: ${var:-word}

${var:-word} gives word when var is unset or empty, and gives the value of var otherwise. The variable itself is not changed:

cat > d2.sh <<'EOF'
unset name
echo "Hello, ${name:-stranger}!"
echo "name is still: [${name-<unset>}]"
name=Ana
echo "Hello, ${name:-stranger}!"
EOF
bash d2.sh
Hello, stranger!
name is still: [<unset>]
Hello, Ana!

The first greeting used the default, and the check on the next line proves that name was not created. Once name has a value, the default is ignored.

Defaults for Arguments

Because command-line arguments are positional parameters, they work with the same operators:

cat > d8.sh <<'EOF'
name=${1:-World}
echo "Hello, $name!"
echo "count=${2:-1}"
EOF
bash d8.sh
bash d8.sh Ana 3
bash d8.sh ""
Hello, World!
count=1
Hello, Ana!
count=3
Hello, World!
count=1

An empty argument ("") triggers the colon form, so the default applies there too.

Defaults for Environment Settings

Programs often let the caller override a setting through an environment variable and fall back to a built-in value:

cat > d14.sh <<'EOF'
port=${PORT:-8080}
echo "port=$port"
EOF
bash d14.sh
PORT=3000 bash d14.sh
PORT= bash d14.sh
port=8080
port=3000
port=8080

The third run set PORT to an empty string. Because the script used :-, an empty value was treated like a missing one. With ${PORT-8080} the third run would have produced an empty port.

The Default Can Be an Expansion

The word after the operator is expanded like any other text, so it can be a variable, a command substitution, or another default expression:

cat > nick.sh <<'EOF'
NICK=ana
user=${USER_NAME:-${NICK:-unknown}}
echo "user=$user"
USER_NAME=suriya
user=${USER_NAME:-${NICK:-unknown}}
echo "user=$user"
unset NICK USER_NAME
user=${USER_NAME:-${NICK:-unknown}}
echo "user=$user"
EOF
bash nick.sh
user=ana
user=suriya
user=unknown

The expression tries USER_NAME first, then NICK, and finally the literal word unknown. Writing a command substitution as the default also works, for example ${DATE:-$(date +%F)}. The command runs only when the default is actually needed.

Assigning a Default: ${var:=word}

${var:=word} works like :-, but it also stores word in the variable when the default is used:

cat > d3.sh <<'EOF'
unset dir
echo "dir before: [${dir-<unset>}]"
echo "using: ${dir:=/tmp/work}"
echo "dir after: [$dir]"
echo "second use: ${dir:=/other}"
EOF
bash d3.sh
dir before: [<unset>]
using: /tmp/work
dir after: [/tmp/work]
second use: /tmp/work

The first expansion created dir. The second := found a value and left it alone.

The Colon Command Idiom

If you only want to ensure that a variable has a value and do not need to print it, the null command : is useful. It does nothing, but Bash still expands its arguments, so the assignment happens:

cat > d3b.sh <<'EOF'
: "${LOG_LEVEL:=info}"
echo "LOG_LEVEL=$LOG_LEVEL"
LOG_LEVEL=debug
: "${LOG_LEVEL:=info}"
echo "LOG_LEVEL=$LOG_LEVEL"
EOF
bash d3b.sh
LOG_LEVEL=info
LOG_LEVEL=debug

The first : line set the missing variable, and the second left debug untouched. The quotes protect the value from word splitting.

The Difference Between = and :=

cat > d4.sh <<'EOF'
empty=""
echo "[${empty=filled}]"
echo "[${empty:=filled}]"
echo "empty now: [$empty]"
EOF
bash d4.sh
[]
[filled]
empty now: [filled]

Without the colon, an empty-but-set variable is accepted as it is. With the colon, it is replaced.

Positional Parameters Cannot Be Assigned

The := form assigns to a real variable, so it is not allowed for $1, $2 and the other positional parameters:

cat > d9.sh <<'EOF'
echo "${1:=x}"
echo "status=$?"
EOF
bash d9.sh
d9.sh: line 1: $1: cannot assign in this way
status=1

Use ${1:-x} to read a default, or copy the argument into a normal variable first, as d8.sh did with name=${1:-World}.

Requiring a Value: ${var:?message}

${var:?message} stops the script with an error when the variable is unset or empty. It is a compact way to say "this must be provided":

cat > d5.sh <<'EOF'
unset TARGET
echo "start"
echo "target is ${TARGET:?TARGET must be set}"
echo "never printed"
EOF
bash d5.sh
echo "exit=$?"
start
d5.sh: line 3: TARGET: TARGET must be set
exit=1

Bash printed the variable name and the message to standard error, and the non-interactive script ended with exit status 1, so the last echo never ran. If you leave the message out, Bash supplies a default one:

cat > d6.sh <<'EOF'
unset TARGET
: "${TARGET:?}"
echo "never printed"
EOF
bash d6.sh
echo "exit=$?"
d6.sh: line 2: TARGET: parameter null or not set
exit=1

The colon decides whether an empty value counts as missing:

cat > d7.sh <<'EOF'
TARGET=""
: "${TARGET:?TARGET is empty or unset}"
echo x
EOF
bash d7.sh
echo "exit=$?"
cat > d7b.sh <<'EOF'
TARGET=""
: "${TARGET?TARGET is unset}"
echo "no colon: empty is accepted"
EOF
bash d7b.sh
echo "exit=$?"
d7.sh: line 2: TARGET: TARGET is empty or unset
exit=1
no colon: empty is accepted
exit=0

In an interactive terminal the same error prints a message but does not close your shell. The "stop the script" behavior applies to scripts.

Using an Alternative Value: ${var:+word}

${var:+word} is the opposite of :-. It gives word only when the variable has a value, and gives nothing otherwise. It is handy for adding an optional piece of text or an option:

cat > d10.sh <<'EOF'
verbose=1
echo "flag:${verbose:+ --verbose}"
unset verbose
echo "flag:${verbose:+ --verbose}"
name=Ana
echo "Dear ${name}${title:+, $title}"
title=Dr
echo "Dear ${name}${title:+, $title}"
EOF
bash d10.sh
flag: --verbose
flag:
Dear Ana
Dear Ana, Dr

The text after :+ appears only when the variable is set and non-empty. The value of the variable itself is not printed; the word replaces it. In the second half of the example, the title and its leading comma are added only when title exists.

Quoting and Word Splitting

A default value follows the usual quoting rules. Without quotes, a default made of several words is split into several words when the result is used as a command argument:

cat > d12.sh <<'EOF'
unset a
show() { echo "$# items"; for x in "$@"; do echo "  [$x]"; done; }
show "${a:-two words}"
show ${a:-two words}
EOF
bash d12.sh
1 items
  [two words]
2 items
  [two]
  [words]

Quote the whole expansion, as in "${a:-two words}", so the default stays together. Lesson 55 explains why quoting variables matters.

Defaults with set -u

The set -u option turns a read of an unset variable into an error. A default value is a safe way to read a variable that might not exist, because the expansion handles the missing case before the error can happen:

cat > d13.sh <<'EOF'
set -u
echo "default works with set -u: ${missing:-fallback}"
echo "plain read:"
echo "$missing"
echo "not reached"
EOF
bash d13.sh
default works with set -u: fallback
plain read:
d13.sh: line 4: missing: unbound variable

The expansion with :- succeeded, but the plain read stopped the script. Lessons 119 to 121 look at set -u and related strict-mode options.

Combining Defaults with Other Expansions

A default often feeds into another expansion in the same script. This example chooses a file name and then changes its extension with ${file%.txt}, which removes .txt from the end of the value (lessons 54 and 152 cover that operator):

cat > d15.sh <<'EOF'
file=${1:-report.txt}
echo "${file%.txt}.bak"
EOF
bash d15.sh
bash d15.sh data.txt
report.bak
data.bak

Without an argument the script used report.txt and printed report.bak. With data.txt it printed data.bak.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Default Values with Parameter Expansion and get answers drawn from it.

Signed-in readers only.