Advanced Parameter Expansion
Parameter expansion is the step in which Bash replaces $name or ${name} with the value of a variable. Lesson 54 introduced the basics, and lesson 45 covered default values such as ${name:-default}. Inside the braces, Bash also offers a small toolkit for changing the value as it is expanded: removing prefixes and suffixes, replacing text, cutting out substrings, changing letter case, looking up a variable whose name is stored in another variable, and transforming a value into a safely quoted form.
All of these operations happen inside the shell. No external program such as sed, cut, basename or tr is started, so they are fast, they work the same on every system that has Bash, and they cannot be confused by unusual characters in the way a pipeline can.
path=/var/www/site/assets/logo.final.png
echo "${path##*/}" # logo.final.png (like basename)
echo "${path%/*}" # /var/www/site/assets (like dirname)
echo "${path##*.}" # png (the extension)
The original variable is never changed by these forms. Each expansion produces a new value, which you can print, compare or assign to another variable.
Overview of the Operators
| Form | Result |
|---|---|
${var#pattern} | remove the shortest match of pattern from the start |
${var##pattern} | remove the longest match from the start |
${var%pattern} | remove the shortest match from the end |
${var%%pattern} | remove the longest match from the end |
${var/pattern/text} | replace the first match |
${var//pattern/text} | replace every match |
${var/#pattern/text} | replace a match at the start |
${var/%pattern/text} | replace a match at the end |
${var:offset} / ${var:offset:length} | substring |
${#var} | length in characters |
${var^} / ${var^^} | first character / all characters to upper case |
${var,} / ${var,,} | first character / all characters to lower case |
${!var} | indirect expansion: the value of the variable named by var |
${!prefix*} / ${!prefix@} | names of all variables starting with prefix |
${var@op} | transformations: Q, E, A, a, U, u, L, K |
Patterns in these forms are glob patterns (lesson 52), not regular expressions: * matches any text, ? one character, and [...] one character from a set.
Removing Prefixes and Suffixes
The four removal operators are the workhorses of parameter expansion. The symbols are easy to remember from a US keyboard: # is to the left of $, so it works on the left (start) of the value, and % is to the right, so it works on the right (end). Doubling the symbol makes the match greedy (longest).
path=/var/www/site/assets/logo.final.png
echo "${path#*.}" # shortest prefix ending in "."
echo "${path##*.}" # longest prefix ending in "."
echo "${path%.*}" # shortest suffix starting with "."
echo "${path%%.*}" # longest suffix starting with "."
final.png
png
/var/www/site/assets/logo.final
/var/www/site/assets/logo
How the Matching Works
For ${path#*.}, Bash tries prefixes of the value from the shortest upward and stops at the first one that matches *.. The shortest prefix that ends in a dot is /var/www/site/assets/logo., so that part is removed, leaving final.png. For ${path##*.}, Bash looks for the longest matching prefix, /var/www/site/assets/logo.final., leaving only png.
The same logic applies at the end of the value with % and %%. This explains the common idioms:
| Task | Expansion | Result for logo.final.png |
|---|---|---|
| file extension | ${f##*.} | png |
| name without the last extension | ${f%.*} | logo.final |
| name without any extension | ${f%%.*} | logo |
| file name from a path | ${p##*/} | like basename |
| folder from a path | ${p%/*} | like dirname |
If the pattern does not match, the value is returned unchanged, which is usually what you want: ${f##*.} on a name without a dot returns the whole name, so check with [[ $f == *.* ]] first if that matters.
Quoting the Pattern
When the pattern comes from a variable, the quoting decides whether its characters are treated as wildcards or as literal text:
pat="*.txt"
f="a.txt"
echo "${f%$pat} | ${f%"$pat"}"
f2="x*.txt"
echo "${f2%"*.txt"} ${f2%*.txt}"
a | a.txt
x x*
Unquoted, $pat is a pattern: *.txt matches .txt at the end of a.txt. Quoted, it is literal text: a.txt does not end with the characters *.txt, so nothing is removed. For x*.txt, the quoted version removes the literal *.txt and the unquoted version removes just .txt. Quote the pattern whenever it holds user data that must be matched literally.
Search and Replace
The / operators replace the part of the value that matches a pattern:
s="hello world, hello bash"
echo "${s/hello/hi}" # first match
echo "${s//hello/hi}" # every match
echo "${s/#hello/HI}" # only at the start
echo "${s/%bash/zsh}" # only at the end
echo "${s//o/}" # delete every "o"
hi world, hello bash
hi world, hi bash
HI world, hello bash
hello world, hello zsh
hell wrld, hell bash
An empty replacement deletes the matches. Because the pattern is a glob, ${s//[0-9]/} deletes every digit and ${s//[^a-z]/} keeps only lower-case letters.
A Practical Use: Making a Slug
A slug is a version of a name that is safe for URLs and file names. Combining case conversion with two replacements produces one without any external tool:
file="My Report (final).PDF"
ext="${file##*.}"
echo "${ext,,} ${file%.*}"
slug="${file,,}"
slug="${slug// /-}"
slug="${slug//[^a-z0-9.-]/}"
echo "$slug"
pdf My Report (final)
my-report-final.pdf
Step by step: ${file,,} makes everything lower case; ${slug// /-} turns spaces into dashes; ${slug//[^a-z0-9.-]/} deletes every character that is not a letter, digit, dot or dash (the parentheses).
Substrings and Length
${var:offset:length} cuts out part of a value. Offsets start at 0. A negative offset counts from the end, and it must be separated from the colon by a space (or put in parentheses), otherwise Bash reads :- as the default-value operator from lesson 45.
s="hello world, hello bash"
echo "${#s}" # length
echo "${s:6}" # from position 6 to the end
echo "${s:6:5}" # 5 characters from position 6
echo "${s: -4}" # the last 4 characters
echo "${s: -10:5}" # 5 characters, starting 10 from the end
23
world, hello bash
world
bash
hello
Substrings are useful for fixed-format data such as dates. With d=20261124, the parts are ${d:0:4} (2026), ${d:4:2} (11) and ${d:6:2} (24).
Changing Letter Case
Since Bash 4.0, four operators change letter case:
name="ana maria"
echo "${name^}" # first character upper case
echo "${name^^}" # all upper case
up="HELLO"
echo "${up,,} ${up,}" # all lower case / first character lower case
echo "${name^^[am]}" # only the letters a and m to upper case
Ana maria
ANA MARIA
hello hELLO
AnA MAriA
The optional pattern after the operator limits which characters are converted. A common use is case-insensitive comparison of user answers: if [[ ${answer,,} == y || ${answer,,} == yes ]] accepts Y, yes, YES and Yes alike.
Indirect Expansion and Variable Names
${!name} expands to the value of the variable whose name is stored in name. This lets a script choose a variable at run time:
user_name=ana user_id=1001 user_home=/home/ana
field=user_home
echo "${!field}"
echo "${!user_*}"
/home/ana
user_home user_id user_name
${!user_*} (or ${!user@}, which behaves like "$@" inside double quotes) lists the names of all variables that begin with user_. This makes it easy to print a group of related settings:
for v in "${!user_@}"; do
printf '%-10s = %s\n' "$v" "${!v}"
done
user_home = /home/ana
user_id = 1001
user_name = ana
For associative arrays, ${!array[@]} has a different meaning: it lists the keys (lesson 103). For a new design, a name reference with declare -n (lesson 104) is usually clearer than ${!name}, but indirect expansion remains common in existing scripts.
Parameter Expansion on Arrays
Every operator in this lesson can be applied to all elements of an array at once by using [@]. The operation runs on each element separately:
arr=(report.txt notes.md data.csv)
echo "${arr[@]%.*}" # remove each extension
echo "${arr[@]/#/backup_}" # add a prefix to each element
echo "${arr[@]^}" # capitalise each element
echo "${#arr[@]} ${#arr[1]}" # number of elements / length of element 1
echo "${arr[@]:1:2}" # elements 1 and 2 (a slice)
report notes data
backup_report.txt backup_notes.md backup_data.csv
Report.txt Notes.md Data.csv
3 8
notes.md data.csv
${arr[@]/#/backup_} replaces the empty string at the start of each element, which is the standard way to add a prefix. ${arr[@]/%/.bak} adds a suffix in the same way. Note that ${arr[@]:1:2} on an array slices elements, not characters.
Transformation Operators: ${var@op}
Bash 4.4 introduced operators that transform a value in ways that are hard to achieve otherwise. Bash 5.1 added more.
| Operator | Result | Since |
|---|---|---|
${var@Q} | the value quoted so it can be reused as shell input | 4.4 |
${var@E} | backslash escapes such as \t and \n expanded | 4.4 |
${var@A} | a declare command that recreates the variable | 4.4 |
${var@a} | the variable's attribute letters (a array, A associative, i integer, r read-only, x exported) | 4.4 |
${var@U} / ${var@u} / ${var@L} | upper case / first letter upper case / lower case | 5.1 |
${var@K} | for arrays, key-value pairs quoted for reuse | 5.1 |
str='it'"'"'s a "test"'
echo "${str@Q}"
p='\t tab'
echo "${p@E}"
declare -i num=5
echo "${num@A}"
declare -A cfg=([port]=80 [host]=localhost)
echo "${arr@a} ${cfg@a} ${num@a}"
x="value"
echo "${x@U} ${x@u}"
'it'\''s a "test"'
tab
declare -i num='5'
a A i
VALUE Value
@Q is the most useful in practice. It produces text that Bash would read back as exactly the original value, which makes it ideal for log and debug messages: echo "deleting ${file@Q}" shows clearly where a file name begins and ends, even when it contains spaces, quotes or a trailing newline. @A is useful for saving variables to a file that can later be loaded with source (lesson 95).
Combining Expansions
Parameter expansion cannot be nested with one set of braces applied directly to another (${${path##*/}%.*} is an error), but the pattern part of an expansion can itself contain an expansion. This allows a well-known trick for trimming whitespace from both ends of a value:
line=" trim me "
t="${line#"${line%%[![:space:]]*}"}" # remove leading whitespace
t="${t%"${t##*[![:space:]]}"}" # remove trailing whitespace
echo "[$t]"
[trim me]
Read the first line from the inside out: ${line%%[![:space:]]*} removes everything from the first non-space character to the end, which leaves just the leading spaces. That result, quoted so it is taken literally, is then removed from the start of line with #. The second line does the same for the end of the value.
For steps that do not fit in one expansion, use an intermediate variable. It costs nothing and makes the code easier to read:
base=${path##*/} # logo.final.png
stem=${base%.*} # logo.final
printf -v (lesson 30) complements parameter expansion for formatting, for example zero-padding a number:
n=7
printf -v padded '%03d' "$n"
echo "$padded"
007
A Complete Example: Parsing URLs Without External Tools
parse-url.sh splits URLs into scheme, user, host, port, path, file name, query string and fragment, using only parameter expansion. It fills in the default port for known schemes, normalises the case of the scheme and host, and reports URLs it cannot parse.
#!/usr/bin/env bash
# parse-url.sh: split URLs into their parts using only parameter expansion
# usage: parse-url.sh URL...
set -u
declare -A default_port=([http]=80 [https]=443 [ftp]=21 [ssh]=22)
parse_url() {
local url=$1 scheme rest authority userinfo user host port path file query fragment
if [[ $url != *://* ]]; then
echo "error: no scheme in '$url'" >&2
return 1
fi
scheme=${url%%://*}
scheme=${scheme,,} # HTTPS -> https
rest=${url#*://}
fragment=""
if [[ $rest == *'#'* ]]; then
fragment=${rest#*'#'}
rest=${rest%%'#'*}
fi
query=""
if [[ $rest == *'?'* ]]; then
query=${rest#*'?'}
rest=${rest%%'?'*}
fi
authority=${rest%%/*} # everything before the first /
if [[ $rest == */* ]]; then
path=/${rest#*/}
else
path=/
fi
userinfo=""
if [[ $authority == *@* ]]; then
userinfo=${authority%@*}
authority=${authority##*@}
fi
host=${authority%%:*}
port=""
[[ $authority == *:* ]] && port=${authority##*:}
port=${port:-${default_port[$scheme]:-unknown}}
if [[ -z $host ]]; then
echo "error: no host in '$url'" >&2
return 1
fi
user=${userinfo%%:*} # drop a password after the colon
file=${path##*/}
printf '%-9s %s\n' \
scheme: "$scheme" \
user: "${user:-(none)}" \
host: "${host,,}" \
port: "$port" \
path: "$path" \
file: "${file:-(none)}" \
query: "${query:-(none)}" \
fragment: "${fragment:-(none)}"
}
status=0
for url in "$@"; do
echo "== $url"
parse_url "$url" || status=1
done
exit "$status"
How It Works
A URL has the general shape scheme://user:password@host:port/path?query#fragment, and the function peels it apart from the outside in:
${url%%://*}removes the longest suffix starting with://, leaving the scheme;${scheme,,}makes it lower case.${url#*://}removes the scheme and://, leaving the rest.- The fragment is removed first, because it is the last part and may itself contain
?or/.${rest#*'#'}keeps what follows the first#, and${rest%%'#'*}keeps what comes before it. The#is quoted so that it is not read as the#operator. - The query is handled the same way with
?, which is quoted because an unquoted?is a wildcard for one character. ${rest%%/*}keeps everything before the first slash, the "authority" part (user:password@host:port). If a slash exists,${rest#*/}gives the path, and a missing path becomes/.${authority%@*}and${authority##*@}split off the user information at the last@, so a password containing@is still handled.${userinfo%%:*}keeps only the user name, so the password is never printed.${authority%%:*}gives the host and${authority##*:}the port.${port:-${default_port[$scheme]:-unknown}}uses nested defaults: an explicit port first, then the scheme's usual port from the associative array, thenunknown.${host,,}normalises the host name, because host names are not case-sensitive.${path##*/}extracts the file name, and${file:-(none)}shows a placeholder when the path ends in/.statusrecords whether any URL failed, so the script exits with 1 if at least one could not be parsed.
This parser deliberately handles common URLs only. It does not decode percent-encoded characters such as %20, and it does not understand IPv6 addresses in brackets.
Running the Complete Example
./parse-url.sh 'HTTPS://Ana:secret@Example.COM:8443/docs/guide.html?lang=en&v=2#install' \
'http://example.com' 'ftp://files.example.org/pub/' \
'example.com/page' 'https:///nohost' 'gopher://old.example.net:70'
echo "status $?"
== HTTPS://Ana:secret@Example.COM:8443/docs/guide.html?lang=en&v=2#install
scheme: https
user: Ana
host: example.com
port: 8443
path: /docs/guide.html
file: guide.html
query: lang=en&v=2
fragment: install
== http://example.com
scheme: http
user: (none)
host: example.com
port: 80
path: /
file: (none)
query: (none)
fragment: (none)
== ftp://files.example.org/pub/
scheme: ftp
user: (none)
host: files.example.org
port: 21
path: /pub/
file: (none)
query: (none)
fragment: (none)
== example.com/page
error: no scheme in 'example.com/page'
== https:///nohost
error: no host in 'https:///nohost'
== gopher://old.example.net:70
scheme: gopher
user: (none)
host: old.example.net
port: 70
path: /
file: (none)
query: (none)
fragment: (none)
status 1
The first URL exercises every part: the upper-case scheme and host were normalised, the password secret was dropped, and the query and fragment were separated correctly. The plain http://example.com received port 80 from the defaults table and the path /. The two malformed URLs produced clear errors and made the final status 1, while the gopher URL, which is not in the defaults table, worked because it gave its port explicitly. The URLs are in single quotes on the command line because &, ? and # are special characters to the shell (lesson 47).