BASH / CHAPTER 02
Parameter expansion and missing-value policy
IntermediateChoose defaults that preserve the distinction between empty and unset.
By the end of this chapter
- Distinguish unset from empty variables
- Choose expansion operators deliberately
- Keep expanded data quoted
The idea
Parameter expansion can supply a fallback without launching another command. ${name-default} uses the default only when name is unset, while ${name:-default} also treats an empty value as missing. That colon changes the policy and matters when an empty string is a legitimate setting. Decide the intended contract before selecting the shorter-looking expression.
Expansion does not remove the need for quoting. Put double quotes around an expanded value when it must remain one argument, including when it contains spaces or is empty. Prefix and suffix removal operators can transform a value without external tools, but their patterns follow shell pattern rules rather than regular-expression rules. Preserve the original when the transformation is only for display, and distinguish deriving a result from assigning a default into the variable itself.
value=''
printf '<%s>\n' "${value-fallback}"
printf '<%s>\n' "${value:-fallback}"<> <fallback>
The first expansion preserves an explicitly empty value; the second substitutes for both unset and empty values.
Try it yourself
Write a fallback that preserves an empty setting but substitutes for an unset variable.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING