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.
file=report
echo "${file}_v2.txt"
echo "$file_v2.txt"report_v2.txt
.txtThe 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.
name=''
echo "${name:-guest}"
echo "${name:=guest}"
echo "$name"guest
guest
guestThe 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.
path=/var/log/report.final.txt
echo "${path##*/}"
echo "${path%.*}"
echo "${path%%.*}"report.final.txt
/var/log/report.final
/var/logThe 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.
s='banana'
echo "${#s}"
echo "${s:2:3}"
echo "${s/an/AN}"
echo "${s//an/AN}"6
nan
bANana
bANANaCase 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.