Parameter expansion manipulates strings in variable values—defaults, substring, and pattern removal—without calling external tools.
Defaults and assign-default
echo "${NAME:-guest}"
: "${COUNT:=0}"
echo "COUNT=$COUNT":= assigns if unset or null; :- only substitutes for the expansion.
Substring and length
file="report-2024-05.txt"
echo "${file:0:7}"
echo "len=${#file}"${var:offset:length} slices strings—handy for parsing fixed-width names.
Pattern removal
path="/var/www/html/index.html"
echo "${path##*/}" # basename
echo "${path%/*}" # dirname style## longest match from front; % shortest from end—powerful but read carefully.
Important interview questions and answers
- Q: ${var:-default} vs ${var:=default}?
A: :- substitutes; := also assigns default to var when unset/null. - Q: What does ##*/ remove?
A: Longest prefix matching */ leaving the filename.
Self-check
- Which expansion provides a default without assignment?
- What operator gives string length?
Tip: ${var:-default} avoids unset surprises—common in deploy scripts.
Interview prep
- ${var:-def}?
Use default if unset/null without assignment.
- ${var##*/}?
Remove longest prefix matching */ (basename style).