Bash Tutorial · Bash Scripting · Lesson 15 of 30
Bash Parameter Expansion
Defaults, string length, substrings and search-and-replace inside variables, without extra commands.
Defaults
${VAR:-default}uses a default when VAR is unset or empty.${VAR:?message}stops the script with an error when VAR is missing; great for required settings.
String operations
| Syntax | Result |
|---|---|
${#s} |
length |
${s:0:4} |
substring (offset, length) |
${s#prefix} / ${s%suffix} |
remove the shortest matching prefix/suffix |
${s##*/} / ${s%/*} |
file name / directory of a path |
${s/old/new} / ${s//old/new} |
replace first / all |
${s^^} / ${s,,} |
upper / lower case |
path="/var/log/nginx/access.log.gz"
echo "${path##*/}"
echo "${path%/*}"
echo "${path%.gz}"
name="ReadyCamel"
echo "${#name} ${name:0:5} ${name^^} ${name,,}"
csv="a,b,c"
echo "${csv//,/ | }"
unset PORT
echo "port: ${PORT:-8080}"
Output
access.log.gz /var/log/nginx /var/log/nginx/access.log 10 Ready READYCAMEL readycamel a | b | c port: 8080
Run this on your computer — see “Get Started” for setup.
Test yourself
What does ${FILE%.txt} do?
Counts .txt filesRemoves .txt from the end of FILEAdds .txt to FILEChecks whether FILE ends in .txt
Show answer
Answer: Removes .txt from the end of FILE