Bash parameter expansion: indirect variables, substitution and sed
Use Bash indirect expansion ${!name}, pattern substitution ${var//pattern/...}, sed for case changes and command substitution.
Bash can transform variable values with parameter expansion, without calling external tools. This article covers indirect expansion, pattern substitution, and text transformation with sed.
Indirect expansion
A variable can hold the name of another variable. ${!name} expands to the value of the variable whose name is stored in name:
part1part2="hello world"
p1="part1"
p2="part2"
p3=$p1$p2
echo $p3
echo ${!p3}
The first echo prints part1part2. The second prints hello world.
Concatenating variables and escaping
part1="Hello"
part2="world"
echo $part1
echo $part2
echo $part1\_$part2
The backslash stops the shell from reading _ as part of the variable name, so the last line prints Hello_world.
Replacing text in a string
${var/pattern/replacement} replaces the first match. ${var//pattern/replacement} replaces every match.
message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
Transforming text with sed
echo 'Hello' | sed 's/.*/\L&/;s/./&\n/g'
This lowercases the line with \L&, then prints each character on its own line.
To count how often each character appears in a file:
sed 's/.*/\L&/;s/./&\n/g' words.txt | sort | uniq -c
Command substitution and building strings
Command substitution stores the output of a command in a variable. $(...) is the preferred form, because it nests more easily than backticks.
ls -l $(which bash)
base_url="https://example.com/some/path"
page="index.html"
# downloads https://example.com/some/path/index.html to downloads/index.html
curl "$base_url/$page" -o "downloads/$page"
Notes
\L(lowercase conversion in the replacement) is a GNU sed extension. It is not available in BSD sed, such as the default sed on macOS.- The
[0-9]bracket expression in${var//pattern/...}is a glob pattern, not a regular expression.