Bash Tutorial · Bash Scripting · Lesson 15 of 30

Bash Parameter Expansion

Defaults, string length, substrings and search-and-replace inside variables, without extra commands.

Create a free account to save this page, take notes and track your progress. Sign in

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
Expansions in action
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?

  1. Counts .txt files
  2. Removes .txt from the end of FILE
  3. Adds .txt to FILE
  4. Checks whether FILE ends in .txt
Show answer

Answer: Removes .txt from the end of FILE

Was this page helpful?