Parameter Expansion Basics
Parameter expansion is the part of Bash that replaces $name with the value of a variable, and it can do much more than that. Inside the braces form ${...} you can ask for a variable's length, cut out part of its value, remove a prefix or suffix, replace text, and change letter case, all without starting another program. This lesson covers the everyday operations. A later lesson covers the advanced ones.
Understanding the Concept
A parameter is anything that holds a value: a variable such as name, a positional parameter such as 1, a special parameter such as #, or an array element. Writing $name asks Bash to put the value in place. Writing ${name} does the same, and ${name...} with an operator after the name asks Bash to transform the value first.
Two facts to keep in mind throughout:
- The expansion produces text. It does not change the variable itself, unless the operator is one of the assignment forms such as
${var:=value}. - The result is subject to word splitting and filename expansion if it is not quoted, like any other expansion.
t="one fish two fish"
echo "${t/fish/cat}"
echo "$t"
Output:
one cat two fish
one fish two fish
The first command printed a changed copy. The variable t still holds the original text.
Braces Around Variable Names
The braces tell Bash exactly where the variable name ends. They are optional when the character after the name cannot be part of a name, and required when it can:
name="Ada"
echo "$nameLovelace|"
echo "${name}Lovelace"
echo "${name}_report"
echo "$name_report|"
Output:
|
AdaLovelace
Ada_report
|
Variable names may contain letters, digits and underscores. Bash read $nameLovelace as a variable of that whole name, which is unset, so the first line printed only the bar. With braces the name stops at }.
Positional parameters need braces once they pass nine:
set -- a b c d e f g h i j k l
echo "$10"
echo "${10}"
echo "${11}"
Output:
a0
j
k
$10 means $1 followed by the character 0, which printed a0. ${10} is the tenth parameter.
String Length
${#name} gives the number of characters in the value:
word="programming"
echo "${#word}"
empty=""
echo "${#empty}"
unset gone
echo "${#gone}"
Output:
11
0
0
An empty variable and an unset one both have length 0. The # has a second use with arrays and positional parameters: ${#arr[@]} is the number of elements, ${#arr[2]} is the length of one element, and ${#} or ${#@} is the number of positional parameters.
arr=(x yy zzz)
echo "${#arr[@]}"
echo "${#arr[2]}"
set -- a b c
echo "${#}"
Output:
3
3
3
The length counts characters or bytes, depending on the locale. For the word café, which contains one accented letter that takes two bytes in UTF-8, the result was 5 in the plain C locale and 4 with LC_ALL=C.UTF-8.
Extracting a Substring
${name:offset:length} returns part of the value, starting at offset (counting from 0) and taking length characters:
s="Hello, World"
echo "${s:7}"
echo "${s:0:5}"
echo "${s:7:3}"
Output:
World
Hello
Wor
${s:7}has no length, so it takes everything from position 7 to the end.${s:0:5}takes five characters from the start.${s:7:3}starts at position 7 and takes three.
A negative offset counts from the end. It must be separated from the colon by a space or placed in parentheses, because :- means something else:
echo "${s: -5}"
echo "${s: -5:3}"
echo "${s:-5}"
Output:
World
Wor
Hello, World
${s:-5} is the "use a default value" operator from the earlier lesson on default values: s is set, so its value was printed unchanged. The offset and length can be arithmetic: ${s:off:5} and ${s:$((off-7)):5} both work. A length longer than the remaining text simply stops at the end, and an offset past the end gives an empty result.
Removing a Prefix or Suffix
Four operators cut text off the beginning or the end of a value by matching a pattern (a glob pattern, not a regular expression):
| Operator | Meaning |
|---|---|
${var#pattern} | Remove the shortest match 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 |
A way to remember them: # appears before a number on a keyboard and works on the front, while % appears after a number and works on the back. Doubling the symbol means "longest".
p="/home/ana/docs/report.final.txt"
echo "${p#*/}"
echo "${p##*/}"
echo "${p#/home/}"
echo "${p#x}"
Output:
home/ana/docs/report.final.txt
report.final.txt
ana/docs/report.final.txt
/home/ana/docs/report.final.txt
*/matches "anything up to a slash". The shortest match is just the leading/, so#removed only that.- With
##, the longest match is everything up to the last slash, leaving the file name. - A pattern that does not match removes nothing, as
${p#x}shows.
The same idea works from the end:
echo "${p%.*}"
echo "${p%%.*}"
echo "${p%/*}"
echo "${p%.txt}"
echo "${p%.csv}"
Output:
/home/ana/docs/report.final
/home/ana/docs/report
/home/ana/docs
/home/ana/docs/report.final
/home/ana/docs/report.final.txt
Taking File Names Apart
With a name that has more than one dot, the short and long forms give different pieces:
file="archive.tar.gz"
echo "name: ${file%%.*}"
echo "everything after the first dot: ${file#*.}"
echo "last extension: ${file##*.}"
echo "without last extension: ${file%.*}"
Output:
name: archive
everything after the first dot: tar.gz
last extension: gz
without last extension: archive.tar
For paths, ${p##*/} does what basename does, and ${p%/*} does what dirname does, without starting a program:
p=/var/log/syslog.1
echo "${p##*/} / $(basename "$p")"
echo "${p%/*} / $(dirname "$p")"
Output:
syslog.1 / syslog.1
/var/log / /var/log
One difference to know: when the value has no slash, ${bare%/*} returns the value unchanged, because nothing matched, while dirname returns ..
Replacing Text
${var/pattern/replacement} replaces the first match of the pattern. A second slash at the front replaces every match:
| Form | Effect |
|---|---|
${var/pat/rep} | Replace the first match |
${var//pat/rep} | Replace all matches |
${var/#pat/rep} | Replace a match at the start |
${var/%pat/rep} | Replace a match at the end |
${var//pat} | Delete all matches |
t="one fish two fish red fish"
echo "${t/fish/cat}"
echo "${t//fish/cat}"
echo "${t/#one/ONE}"
echo "${t/%fish/bird}"
echo "${t//fish}"
Output:
one cat two fish red fish
one cat two cat red cat
ONE fish two fish red fish
one fish two fish red bird
one two red
The pattern accepts wildcards:
echo "${t/f?sh/X}"
echo "${t//[aeiou]/_}"
Output:
one X two fish red fish
_n_ f_sh tw_ f_sh r_d f_sh
To replace a slash, escape it so Bash does not take it for the end of the pattern:
slash="/usr/local/bin"
echo "${slash//\//:}"
path_dots="a.b.c"
echo "${path_dots//./-}"
Output:
:usr:local:bin
a-b-c
The Ampersand in Bash 5.2
In Bash 5.2 and later, an unquoted & in the replacement stands for the text that was matched. This is the patsub_replacement option, on by default. Use a backslash to get a literal ampersand:
x=abc
echo "${x/b/[&]}"
echo "${x/b/[\&]}"
Output:
a[b]c
a[&]c
In the pattern itself, an ampersand is an ordinary character, so ${amp/&/and} turns Tom & Jerry into Tom and Jerry.
Changing Letter Case
Bash can change case with four operators. A single symbol changes the first character, and a doubled symbol changes every character:
| Form | Effect |
|---|---|
${var^} | First character to upper case |
${var^^} | All characters to upper case |
${var,} | First character to lower case |
${var,,} | All characters to lower case |
m="hello World"
echo "${m^}"
echo "${m^^}"
echo "${m,,}"
echo "${m,}"
Output:
Hello World
HELLO WORLD
hello world
hello World
An optional pattern restricts which characters change:
echo "${m^^[a-e]}"
Output:
hEllo WorlD
Only the letters from a to e were changed to upper case, which affected the e in "hello" and the d in "World".
Patterns Stored in Variables
The pattern part can come from a variable. When it is unquoted, its wildcard characters work. When it is quoted, they are taken literally:
suffix=".txt"
fn="notes.txt"
echo "${fn%$suffix}"
sv="xaXXbz"
star="a*b"
echo "${sv/$star/Q}"
echo "${sv/"$star"/Q}"
Output:
notes
xQz
xaXXbz
The unquoted $star acted as the pattern a*b, which matched aXXb. The quoted "$star" was the literal text a*b, which does not occur in xaXXbz.
Applying Expansions to Many Values
On positional parameters and arrays, the operators apply to each element:
set -- apple banana cherry
echo "${@/a/A}"
echo "${@:2}"
echo "${1^^}"
fruit=(apple banana cherry)
echo "${fruit[@]^^}"
echo "${fruit[1]:0:3}"
echo "${fruit[@]%e}"
Output:
Apple bAnana cherry
banana cherry
APPLE
APPLE BANANA CHERRY
ban
appl banana cherry
${@:2} takes every parameter from the second onwards, which is the same offset idea as for strings. ${fruit[@]%e} removed a trailing e from each element separately; only apple ended in e.
Practical Applications
Changing File Extensions
for f in *.jpeg; do echo "$f -> ${f%.jpeg}.jpg"; done
Output (in a folder with a.jpeg and b.jpeg):
a.jpeg -> a.jpg
b.jpeg -> b.jpg
Replacing echo with mv "$f" "${f%.jpeg}.jpg" would perform the rename. Run the echo version first to check the names.
Formatting Text
user=ada
echo "Hello, ${user^}!"
t="my report final.txt"
echo "${t// /_}"
Output:
Hello, Ada!
my_report_final.txt
Testing Extensions
for f in report.txt data.csv; do
case $f in
*.txt) echo "${f%.txt} is text";;
*.csv) echo "${f%.csv} is csv";;
esac
done
Output:
report is text
data is csv
Availability in Other Shells
The operators ${#var}, #, ##, % and %% are part of the POSIX standard and work in Dash:
sh -c 'v=report.txt; echo "${v%.txt}"; echo "${v#rep}"; echo "${#v}"'
Output:
report
ort.txt
10
Substrings, replacement and case changes are Bash features. Dash rejects them:
sh -c 'v=hello; echo "${v^^}"'
Output:
sh: 1: Bad substitution
A script that starts with #!/bin/sh should therefore use only the first group, or call sed, tr and similar programs instead. Other expansions, such as indirect expansion with ${!name}, are covered in the lesson on advanced parameter expansion.