Skip to content
Parameter Expansion
step 1/4

Reading — step 1 of 4

Learn

~1 min readParameter Expansion and Patterns

Bash's parameter expansion (${var...}) replaces a small standard library of string operations.

Defaults and length:

echo "${name:-default}"        # value, or 'default' if unset/empty
echo "${name:=default}"        # also assigns to name
echo "${name:?error msg}"      # error and exit if empty
echo "${#name}"                # length

Substring:

s="hello world"
echo "${s:0:5}"                # hello (start:length)
echo "${s:6}"                  # world (from offset)
echo "${s: -5}"                # world (from end — note the space!)

Pattern removal — strip a glob from the start or end:

file="document.tar.gz"
echo "${file%.gz}"             # document.tar (remove shortest match from end)
echo "${file%%.*}"             # document (remove longest match from end)
echo "${file#*.}"              # tar.gz (remove shortest from start)
echo "${file##*.}"             # gz (remove longest from start — i.e. extension)

Mnemonic: # looks like the start of a line, % looks like a percent sign at the end.

Substitution:

s="hello world hello"
echo "${s/hello/HI}"           # HI world hello (first match)
echo "${s//hello/HI}"          # HI world HI (all matches — note //)
echo "${s/hello/}"             # ' world hello' (delete first)

Case conversion (Bash 4+):

s="Hello World"
echo "${s^^}"                  # HELLO WORLD
echo "${s,,}"                   # hello world
echo "${s^}"                    # Hello World (first char only)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…