Menu
CoddyTech

Default Values

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 18 of 39.

${var:-default} expands to the variable's value, or to default when the variable is unset or empty. It works on arguments and on any other variable:

#!/bin/bash
name=${1:-guest}
echo "Hi, $name. Theme: ${THEME:-light}"
echo "Tries: ${TRIES:=3}"
echo "Saved: $TRIES"

bash hi.sh prints Hi, guest. Theme: light. THEME=dark bash hi.sh Ana sets THEME for that one command and prints Hi, Ana. Theme: dark. ${TRIES:=3} also stores the default in the variable, so the last line prints Saved: 3; it cannot store into $1.

${var:?message} stops the script when the value is missing. Bash prints the message to stderr, after the script name, the line number and the variable, and the script exits with code 1:

#!/bin/bash
file=${1:?give a file name}
wc -l "$file"

bash lines.sh prints lines.sh: line 2: 1: give a file name and never reaches wc.

challenge icon

Challenge

Medium

Write a coffee script that fills in a default size and cup, and refuses to run without a drink.

  1. Open brew.sh.
  2. Store the first argument in drink with ${1:?...}, so a missing drink stops the script with the message need a drink.
  3. Store the second argument in size, with medium as its default.
  4. Print Making a SIZE DRINK in a CUP cup, where CUP is the environment variable CUP, or paper when it is unset or empty.
  5. Save the file.

Try it: run bash brew.sh tea. It prints:

Making a medium tea in a paper cup

Then run CUP=glass bash brew.sh latte small:

Making a small latte in a glass cup

Run bash brew.sh with no drink: it prints an error ending in 1: need a drink to stderr and exits 1.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground