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
MediumWrite a coffee script that fills in a default size and cup, and refuses to run without a drink.
- Open
brew.sh. - Store the first argument in
drinkwith${1:?...}, so a missing drink stops the script with the messageneed a drink. - Store the second argument in
size, withmediumas its default. - Print
Making a SIZE DRINK in a CUP cup, where CUP is the environment variableCUP, orpaperwhen it is unset or empty. - Save the file.
Try it: run bash brew.sh tea. It prints:
Making a medium tea in a paper cupThen run CUP=glass bash brew.sh latte small:
Making a small latte in a glass cupRun bash brew.sh with no drink: it prints an error ending in 1: need a drink to stderr and exits 1.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter4Strings And Arrays
Slicing StringsTrimming And ReplacingDefault ValuesArraysReading Files Line By LineRecap - CSV ReportPractice on your own: Terminal playground