$_ CLI In Depth
Learning progress 0%
lesson expansion quoting word-splitting

Variable & Parameter Expansion

5 min read Module 8: Expansion, Quoting & Word Splitting Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:23

Plain and braced forms

The expansion $name is replaced by the value of the variable name. The braces, as in ${name}, mark where the name ends. You need them when text follows the name directly, because $names refers to a variable called names, not to name followed by an s. The braces are also required for the operators that come later in this lesson. If a variable is unset, both forms expand to an empty string, unless the shell is set to treat unset variables as errors with set -u.

BASH3 lines
file=report
echo "${file}_v2.txt"
echo "$file_v2.txt"
TEXT2 lines
report_v2.txt
.txt

The second line printed .txt because bash looked for a variable named file_v2, which does not exist. Braces are cheap insurance, and many style guides recommend them whenever a variable sits next to other text.

Defaults and assignments

The operators ${name:-word}, ${name:=word}, ${name:+word}, and ${name:?message} test whether a variable is unset or empty. The colon makes the test cover both cases. Without the colon, only an unset variable counts. The first form uses word when the variable is empty or unset, and leaves the variable alone. The second does the same and also assigns word to the variable. The third does the opposite: it produces word only when the variable has a non-empty value. The fourth stops with an error message when the variable is empty or unset, and it is a good way to make a script refuse to run without a required setting.

BASH4 lines
name=''
echo "${name:-guest}"
echo "${name:=guest}"
echo "$name"
TEXT3 lines
guest
guest
guest

The first line used the default but did not change name. The second line assigned the default, so the third line shows the new value. Use :- for a fallback in a read-only context, and reserve := for variables you intend to set.

Trimming prefixes and suffixes

The pattern operators remove text from the start or the end of a value. ${file#pattern} removes the shortest match from the start, and ${file##pattern} removes the longest match. ${file%pattern} and ${file%%pattern} do the same from the end. The patterns use the filename-style syntax from the previous lesson, so * means any run of characters.

The most common use is splitting a path. The pattern */ matches everything up to the last slash when you use the longest form, so ${path##*/} is the base name. The pattern .* matches from a dot to the end, so the shortest suffix form ${path%.*} removes only the final extension.

BASH4 lines
path=/var/log/report.final.txt
echo "${path##*/}"
echo "${path%.*}"
echo "${path%%.*}"
TEXT3 lines
report.final.txt
/var/log/report.final
/var/log

The last line shows the difference between the short and long forms. Removing the longest suffix that starts with a dot deleted everything from the first dot onward, which in this path is the start of .final.txt. Decide which one you want before you write the expansion.

Defaults in a real script

The default and error forms earn their place at the top of a script. Suppose a backup script needs a destination, and the user may supply it through the environment. The line dest=${BACKUP_DIR:-/workspace/backups} gives the script a sensible value without an if statement. The line : ${BACKUP_DIR:?set BACKUP_DIR first} does the opposite: it checks the value and stops with the message when the value is missing. The leading colon is a no-op command, so the expansion is evaluated only for its side effect. Use the error form for settings that have no reasonable default, because a clear message at the top of a script is much easier to debug than a failure three commands later.

The assign form, ${name:=word}, is useful for the same purpose when you want the value to persist for the rest of the script. Use it sparingly. Each time it runs, the variable changes, and a reader has to track where that change happened. Setting the default on a separate line is usually clearer.

The alternate-value operator

The fourth form, ${name:+word}, is the inverse of the default. It produces word only when name is set and not empty, and it produces nothing otherwise. Scripts use it to add an optional flag. The line echo "tool${verbose:+ --verbose}" adds the flag when verbose has a value and leaves the command unchanged when it does not. Because the substituted text is inside double quotes, the leading space is kept, so the flag is separated from the command name.

Length, slicing, and replacement

${#name} gives the number of characters in the value. ${name:offset:length} returns a substring, with the offset counted from zero. A negative offset must be separated from the colon by a space, as in ${name: -3}. ${name/pattern/replacement} replaces the first match, and the doubled slash replaces every match. These forms cover much of what cut and a one-line sed would otherwise do, and they run without starting a process.

BASH5 lines
s='banana'
echo "${#s}"
echo "${s:2:3}"
echo "${s/an/AN}"
echo "${s//an/AN}"
TEXT4 lines
6
nan
bANana
bANANa

Case conversion

Bash 4 and later can change case inside an expansion. ${name^} uppercases the first character, ${name^^} uppercases everything, and ${name,,} lowercases everything. These operators do not change the variable itself. They only change the text produced by the expansion, so assign the result if you need to keep it.

Where the forms stop

Parameter expansion works on one value at a time. It does not loop, it cannot modify several variables at once, and it does not understand regular expressions. For arrays and for prefix matching of variable names, the syntax grows more elaborate, and a later module covers arrays. When a transformation needs a real regular expression or several passes over a file, a tool such as sed or awk is still the right choice. The rule of thumb is simple: if the job is to read one value and produce a modified version of it, use parameter expansion, because it is faster and avoids quoting problems in a pipe.

The order of shell expansions

Visualizer

Bash rewrites each word in a fixed sequence: braces, tilde, parameters and substitutions, word splitting, pathnames, then quote removal.

1 / 6
the line as typed
echoword 0
~/"$name"word 1
$(date +%Y)word 2
*.txtword 3

Bash parses the line into four words. Nothing is expanded yet, so each word is still its literal text.

name="my docs"; printf "[%s]\n" ~/"$name" $(date +%Y) *.txt
Terminal lab · 3 steps · real Linux in your browser

Shape values with parameter expansion

Use defaults, trim a path, and change the case of a value without calling another program.

01
Use a default when a variable is empty
The form ${name:-guest} substitutes guest when name is unset or empty. Set name to an empty string first so the default takes effect. Run this in /workspace. ``bash name='' echo "${name:-guest}" > greet.txt `` Run cat greet.txt. It should print guest.
Show hint for step 1
Use the colon form with a dash, and write the result to greet.txt.
02
Trim a path into its base name and stem
Use the long prefix form for the base name, and the short suffix form for the stem. The two files are base.txt and stem.txt. ``bash file=/var/log/report.final.txt echo "${file##*/}" > base.txt echo "${file%.*}" > stem.txt `` The base name should be report.final.txt, and the stem should be /var/log/report.final.
Show hint for step 2
Use ${file##*/} for the base name and ${file%.*} for the stem. Write each result on its own line in a file.
03
Measure a word and change its case
The operator ${#word} returns the number of characters, and ${word^^} returns the uppercase form. Both are expansions, so they run inside the same echo. ``bash word=bash echo "${word^^} ${#word}" > shout.txt `` The file should contain BASH and then 4.
Show hint for step 3
Put the length and the uppercase form inside one double-quoted echo, separated by a space. Write to shout.txt.
Check yourself Question 1 of 4
Concept Check Default operator recall

With name unset, which expression prints guest and leaves name unset?

Recap & Key Takeaways

Braces mark the end of a variable name, which matters when text follows it directly, as in ${file}_v2.txt.
The colon in ${name:-word} makes the test cover both unset and empty values; without it, only unset counts.
${path##*/} gives the base name and ${path%.*} removes the last extension.
${#name}, ${name:offset:length}, and the slash forms slice and replace text without starting another program.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue