Parameter Expansion and String Surgery

Parameter Expansion and String Surgery in Bash: At the back of a menswear shop stands the alterations bench, and behind it a tailor who never guesses.

The Analogy: The Tailor's Alterations Bench

At the back of a menswear shop stands the alterations bench, and behind it a tailor who never guesses. Every garment that arrives comes pinned to a job ticket, and the ticket carries the measurements: take up the hem by three centimetres, replace the worn cuff button, let the waist out to ninety-two. The tailor reads the ticket, lays the garment flat, and reaches for one of a small set of trusted tools -- the tape measure, the shears, the seam unpicker, and a tin of spare buttons that matches almost anything. Nothing is done by eye; everything is measured, marked with chalk, and cut to the mark.

Each tool does one bounded job. The tape measures a length and reports a number. The shears trim cloth from an edge -- and it matters which edge, because hemming the bottom is a different operation from taking in a sleeve. The unpicker removes stitching either up to the nearest seam or, if the ticket says so, all the way back to the last seam of that kind. The button tin supplies a replacement only when the customer did not bring their own; if they did, the tin stays shut. Every operation starts from the value written on the ticket and produces a finished result on a fresh hanger.

When the ticket says "remove the contrast trim," the tailor has a choice of appetite. The cautious cut takes only the nearest band of trim and leaves the rest; the greedy cut strips every band back to the last plain seam. The same shears, the same edge, but a different reach. A skilled tailor knows which the customer meant, and a good shop writes it on the ticket so there is no doubt. The altered garment then goes out tagged and ready for collection.

Here is the part that trips up the apprentice. The tailor works from the ticket's copy of the measurements and hands back the altered garment on a new hanger -- the bolt of cloth in the stockroom is never touched. If you expected the stockroom to change because you altered one suit, you have misread the bench. And the shop's pattern stencils are simple shapes, not a draughtsman's precise curves: ask the bench to "match a serial-number pattern" the way a machinist would, and it will take your stencil literally and cut the wrong cloth.


Syntax or Core Structure

Parameter expansion is Bash reading a value off a variable and reshaping it before the command ever runs. The value on the variable is the bolt of cloth; the expansion is the alteration; the result is a fresh string that the surrounding command receives. The variable itself is not changed unless you assign the result back to it.

The most common expansions read a length, strip a path down to its parts, or pull off an extension. Every one of them is written inside ${ ... } -- the braces are what turn a plain $name into an instruction rather than a simple lookup.

#!/usr/bin/env bash
set -euo pipefail

path="/var/log/app/report.log"

echo "length: ${#path}"      # count the characters
echo "file:   ${path##*/}"   # strip everything up to the last /
echo "dir:    ${path%/*}"    # strip the last / and what follows
echo "ext:    ${path##*.}"   # strip up to the last dot

base="${path##*/}"
echo "stem:   ${base%.*}"    # drop the extension from the file

Output:

length: 23
file:   report.log
dir:    /var/log/app
ext:    log
stem:   report

The value in path is twenty-three characters long, so ${#path} reports 23. The ## operator strips the longest match from the front, so ${path##*/} removes /var/log/app/ and leaves the file name. The % operator works from the back: ${path%/*} removes the shortest trailing /... and leaves the directory. Chaining two expansions -- first cut the directory away, then cut the extension -- gives the bare stem, which is how scripts derive names without ever shelling out to basename or dirname.


Technical Depth: Every Cut the Bench Can Make

Defaults, assignment, and required values

Four expansions handle missing or empty values, and the colon in each one means "treat empty the same as unset." ${var:-word} supplies word when var is unset or empty but leaves var alone. ${var:=word} does the same and also assigns word back to var. ${var:+word} is the mirror image: it yields word only when var is set and non-empty. ${var:?word} aborts the script with word as the error when var is missing, which is how you demand an input.

ExpansionIf var is set and non-emptyIf var is unset or empty
${var:-word}value of varword (var unchanged)
${var:=word}value of varword (and var is assigned word)
${var:+word}wordempty string
${var:?word}value of varprint word to stderr, exit 1
#!/usr/bin/env bash
set -uo pipefail

unset name
echo "hi ${name:-guest}"       # name unset -> use guest
echo "still: ${name:-none}"    # still unset -> none

: "${name:=anon}"              # now assign a default into name
echo "now: $name"              # anon

unset verbose
echo "flag:[${verbose:+on}]"   # unset -> empty
verbose=1
echo "flag:[${verbose:+on}]"   # set -> on

if ( : "${missing:?unset}" ) 2>/dev/null; then
  echo "ok"
else
  echo "guarded exit: $?"
fi

Output:

hi guest
still: none
now: anon
flag:[]
flag:[on]
guarded exit: 1

Notice that :- and :+ never touch the variable, while := writes into it -- the colon-equals is the only one of the four with a side effect. The :? guard runs inside a subshell here so its non-zero exit is caught by the if rather than ending the whole script; on its own line at the top of a script it is the standard way to fail fast when a required argument is absent.

Trimming from the front and the back

The four trimming operators come as a matched set: # and ## cut from the front, % and %% cut from the back, and doubling the symbol makes the cut greedy (longest match instead of shortest). The pattern after the symbol is a glob, so * means "any run of characters."

OperatorCuts fromMatch lengtharchive.tar.gz gives
${v%.*}backshortestarchive.tar
${v%%.*}backlongestarchive
${v#*.}frontshortesttar.gz
${v##*.}frontlongestgz
#!/usr/bin/env bash
set -euo pipefail

file="archive.tar.gz"
echo "${file%.*}"    # drop the last .something
echo "${file%%.*}"   # drop everything from the first dot
echo "${file#*.}"    # drop up to the first dot
echo "${file##*.}"   # keep only the final extension

Output:

archive.tar
archive
tar.gz
gz

A common mnemonic ties each symbol to its place around the $: on a US keyboard # sits to the left of $ and trims the left (front) of the value, while % sits to the right and trims the right (back). Reach for %% when a file has several extensions and you want the true stem, and for ## when you want the innermost extension regardless of how many dots precede it.

Substituting content and changing case

${var/pat/rep} replaces the first match of a glob pattern; doubling the slash to ${var//pat/rep} replaces every match. Anchoring with ${var/#pat/rep} forces the match at the start and ${var/%pat/rep} at the end. Case conversion uses ${var^^} to upper-case and ${var,,} to lower-case the whole value.

ExpansionMeaningResult
${csv/,/;}replace first commaa;b,c,d
${csv//,/;}replace every commaa;b;c;d
${greet/#hello/hi}replace only if at the starthi world
${greet/%world/all}replace only if at the endhello all
${name^^}upper-case the whole valueMIXEDCASE
#!/usr/bin/env bash
set -euo pipefail

csv="a,b,c,d"
echo "${csv/,/;}"
echo "${csv//,/;}"

name="mixedCASE"
echo "${name^^}"
echo "${name,,}"

greet="hello world"
echo "${greet/#hello/hi}"
echo "${greet/%world/all}"

Output:

a;b,c,d
a;b;c;d
MIXEDCASE
mixedcase
hi world
hello all

The pattern is still a glob, not a regular expression: a * or ? in the search half is a wildcard, and a regex construct like a digit class simply will not work here. Case folding is the cheapest way to normalise user input before comparison, and it avoids piping through tr for a job the shell can do in place.

Slicing out a substring by position

${var:offset:length} returns length characters starting at a zero-based offset, and ${var:offset} runs to the end. A negative offset counts from the right, but it must be written with a leading space (or wrapped in parentheses) so Bash does not read it as the :- default operator.

#!/usr/bin/env bash
set -euo pipefail

s="2026-09-24"
echo "${s:0:4}"    # year
echo "${s:5:2}"    # month
echo "${s:5}"      # month-day to the end
echo "${s: -2}"    # last two, note the space

Output:

2026
09
09-24
24

Offsets past the end of the string yield an empty result rather than an error, so a script slicing fixed-width fields out of a record should check the length first with ${#var}. Taken together these operators mean a surprising amount of parsing -- dates, fixed-width fields, simple key=value pairs -- can be done with no external tool at all, which keeps hot loops fast and free of quoting surprises.


Real World Example: Sanitising Uploaded File Names

A web upload form hands the backend whatever the browser sent: names with spaces, mixed case, stray punctuation, and inconsistent extensions. Before those files touch the disk they need to become predictable slugs -- lower-case, underscore-separated, stripped of anything that is not a safe character. The script below does the whole job with parameter expansion and not one external command, which makes it fast enough to run inside a tight upload loop.

#!/usr/bin/env bash
set -euo pipefail

raw=(
  "IMG 0001.JPEG"
  "Q3 (draft).docx"
  "report FINAL.PDF"
  "notes.txt"
)

slugify() {
  local name="$1"
  local base="${name%.*}"          # everything before the last dot
  local ext="${name##*.}"          # the final extension
  ext="${ext,,}"                   # lower-case the extension
  base="${base,,}"                 # lower-case the stem
  base="${base// /_}"              # spaces become underscores
  base="${base//[^a-z0-9_]/}"      # drop anything else
  printf '%s.%s\n' "$base" "$ext"
}

for item in "${raw[@]}"; do
  printf '%-18s -> %s\n' "$item" "$(slugify "$item")"
done

Output:

IMG 0001.JPEG      -> img_0001.jpeg
Q3 (draft).docx    -> q3_draft.docx
report FINAL.PDF   -> report_final.pdf
notes.txt          -> notes.txt

The order of operations inside slugify is deliberate. The extension is split off first with %.* and ##*. so that the dot separating name from extension is not itself treated as punctuation and removed. Both halves are lower-cased with ,, before any character surgery, because the character class in the final step only lists lower-case letters -- fold the case first and an upper-case letter survives as itself rather than being deleted. Spaces are turned into underscores explicitly so they are preserved as word boundaries, and only then does the class ${base//[^a-z0-9_]/} sweep away brackets, symbols, and anything else that is left.

Reading the output confirms each rule: the space in IMG 0001 became an underscore, the parentheses around draft vanished while the word survived, and the upper-case extensions were folded to jpeg and pdf. The printf format pads the original name to eighteen columns so the arrows line up, which is a presentation choice and has nothing to do with the slugging itself.

This works, but it has honest limits. The most important is a real bug hiding in plain sight: a name with no dot at all, such as README, makes both ${name%.*} and ${name##*.} return the entire string unchanged, so the stem and the extension are both README and the slug comes out as readme.readme. The script also has no collision handling -- two different uploads that slug to the same name will silently overwrite each other -- and the character class is ASCII-only, so an accented letter is deleted rather than transliterated, which can turn a meaningful foreign-language name into a shorter, confusing one.


Common Mistakes

  1. Expecting the variable to change. ${var#foo} produces a new value; it does not modify var. You must assign it back with var="${var#foo}" if you want the change to stick.
  2. Confusing # with %. # trims the front and % trims the back. Reaching for ${file#*.} when you wanted the extension gives you everything after the first dot, not the last.
  3. Forgetting the pattern is a glob. The trimming and substitution operators match shell globs, not regular expressions, so a digit class does nothing useful and * is a greedy wildcard rather than a literal star.
  4. Missing the space before a negative offset. ${var:-2} is the default operator (use -2 if var is empty), while ${var: -2} is the last two characters. The space is not optional.
  1. Using :- when you meant :=. ${var:-word} leaves var untouched; if you expected the default to persist for later lines, you needed ${var:=word}.
  2. Assuming :- and - are the same. Without the colon, ${var-word} only substitutes when var is entirely unset; a variable set to the empty string counts as "set" and the default is skipped. The colon adds "or empty."
  3. Leaving the expansion unquoted. echo ${path##*/} without quotes lets the result undergo word splitting and globbing; a name with spaces or a * will break silently. Quote it: "${path##*/}".
  4. Greedy where you wanted lazy, or the reverse. ${host%%.*} on www.example.com returns www, but ${host%.*} returns www.example; doubling the operator changes the answer, and picking the wrong one is a classic domain-parsing bug.
  5. Trying to nest or chain in one set of braces. You cannot apply two operators at once or write one expansion inside another's braces; each operation needs its own expansion, often through an intermediate variable.

Best Practices

  • Quote every expansion in command position. Write "${var##*/}" so the result cannot be split or globbed; the braces protect the syntax, but only quotes protect the value.
  • Prefer parameter expansion over external tools for simple parsing. ${file##*.} is faster and safer than echo | sed for an extension, and it cannot be fooled by a name that looks like an option.
  • Make defaults explicit with :-. "${PORT:-8080}" documents the fallback at the point of use and survives set -u, which would otherwise abort on an unset variable.
  • Demand required inputs early with :?. : "${1:?usage: deploy ENV}" fails with a clear message on line one instead of letting an empty value cause damage later.
  • Match greediness to the data. Use %% and ## when a value has several separators and you want the outermost split; use the single form for the innermost.
  • Fold case before comparing or classifying. "${answer,,}" lets you test against one lower-case form instead of listing every capitalisation.
  • Assign back only when you mean to mutate. Keep read-only expansions inline; use path="${path%/}" to actually change a variable, and say in a comment why.
  • Test patterns against the awkward cases. Names with spaces, no extension, multiple dots, or a leading dot expose most expansion bugs; add them to your fixtures before trusting the code.

Practice Exercises

  1. Path splitter. Given a full path in a variable, print its directory, file name, stem, and extension on four labelled lines using only parameter expansion -- no basename, dirname, or sed.
  2. Config with defaults. Read HOST, PORT, and PROTO from the environment, supply localhost, 8080, and http as defaults with :-, and abort with a helpful message via :? if a required TOKEN is missing.
  3. CSV field masker. Take a line like name,4111111111111111,exp and replace the middle field with asterisks using substitution, keeping the other fields; then note the one thing a glob cannot do here (match the same number of characters it removed).
  4. Slug round-trip. Extend the lesson's slugify to handle a name with no dot correctly (no readme.readme bug) and to append a numeric suffix when two inputs would collide; verify with a fixture list.