← Back to Bash Course | Chapter 13: Advanced Scripting | Lesson 7 of 7

Default/Fallback Argument Handling

A script can supply a sensible default value automatically when the person running it doesn't provide one, instead of failing or leaving a blank.

Providing a Fallback with :-

${var:-default} expands to var's value if it is set and non-empty, or to default otherwise, without modifying var itself. This is the most common way to give an argument a sensible default.

Example: Providing a Fallback with :-

bash
#!/bin/bash
set --
name=${1:-"anonymous"}
echo "Hello, $name"

Assigning the Default Back with :=

${var:=default} behaves like :- but also assigns default into var, so subsequent uses of var see the default too. This only works on ordinary variables, not positional parameters like $1.

Note: The leading : (a no-op command) is a common trick to apply := for its side effect without needing to use the expanded value anywhere.

Example: Assigning the Default Back with :=

bash
#!/bin/bash
unset timeout
: "${timeout:=30}"
echo "timeout is now set to: $timeout"

The Inverse Case with :+

${var:+alt} is the mirror image of :-: it expands to alt only when var is set and non-empty, and to nothing otherwise, which is useful for conditionally including a flag only when a variable is present.

Example: The Inverse Case with :+

bash
#!/bin/bash
verbose="1"
flag=${verbose:+"--verbose"}
echo "flag is: $flag"

unset verbose
flag=${verbose:+"--verbose"}
echo "flag is now: [${flag}]"

Combining Defaults with Validation

Defaults and required-value checks can be combined: give optional settings a fallback with :-, while still using :? for values that truly must be provided by the caller.

Example: Combining Defaults with Validation

bash
#!/bin/bash
set -- "myapp"
app_name=${1:?app name is required}
log_level=${2:-"info"}
echo "starting $app_name with log level $log_level"
Common Mistakes
  1. Confusing ${var:-default} (use default if unset OR empty) with ${var-default} (use default only if unset, empty string is kept as-is).
  2. Using ${var:=default} expecting it to work on positional parameters directly; assignment forms can't assign to $1, $2, etc., only to named variables.
  3. Forgetting ${var:+alt} is the inverse case: it substitutes alt only when var IS set and non-empty, which is easy to mix up with :-.
Chapter Summary
  • ${var:-default} yields default if var is unset or empty, without changing var itself.
  • ${var:=default} does the same but also assigns default back into var (only works on plain variables, not positional parameters).
  • ${var:+alt} yields alt only when var IS set and non-empty; otherwise yields nothing.
  • ${var:?message} errors out immediately with message if var is unset or empty.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.