This page looks best with JavaScript enabled

Bash: Parameter Expansion

 ·   ·  ☕ 1 min read

Bash can transform variables for you as it expands them, with no extra programs like sed or awk. These are called Shell Parameter Expansions, and they are written as ${variable...}.

1
2
3
4
5
file="notes.txt"
echo "${file%.txt}"          # notes
echo "${file^^}"             # NOTES.TXT
echo "${file/notes/todo}"    # todo.txt
echo "${missing:-fallback}"  # fallback

If you want the length of a value, see the quick tip on counting characters in a string.


Sam Wronski
WRITTEN BY
Sam Wronski
Maker of things and professional software engineer. Lets make something awesome together!

Bash parameter expansion

Each ${...} is replaced with a transformed copy of the variable. The original is not changed.

file="notes.txt"
echo "${file%.txt}"          # notes
echo "${file^^}"             # NOTES.TXT
echo "${file/notes/todo}"    # todo.txt
echo "${missing:-fallback}"  # fallback
${file%.txt}
remove the shortest match of the pattern from the end, which strips the extension
${file^^}
convert to uppercase (Bash 4 or newer)
${file/notes/todo}
replace the first match of notes with todo
${missing:-fallback}
use fallback when the variable is unset or empty

Also useful

${#file}
The length of the value in characters.
${file#prefix}
Remove the shortest match of the pattern from the start.

Shell Parameter Expansion in the Bash manual