Bash Shell Expansion and Globbing
last modified October 24, 2026
Before Bash runs a command, it transforms the command line: it expands
braces, the tilde, variables, command substitutions, and arithmetic,
splits the results into words, and replaces glob patterns with matching
file names. Knowing these expansions and their order explains much of
the shell's behaviour, from cp file{,.bak} to the surprises
of unquoted variables.
The examples were run with Bash 5.2 on Debian 12. A directory
glob holds some sample files: text, CSV, and Markdown files,
two images, two hidden files, and a src tree with C
files.
Seeing the expansions
The set -x option prints each command after expansion,
prefixed with +. The commands were typed in an interactive
shell.
set -x
echo ~/{a,b}.txt $((2 + 3)) "$(date +%Y)"
set +x
The command substitution ran first, in a nested level (++).
Then echo received the fully expanded arguments: the braces
produced two words, the tilde became the home directory, and the
arithmetic expression became 5. Bash performs the expansions in this
order: brace expansion; tilde, parameter, and arithmetic expansion and
command substitution (left to right); word splitting; pathname expansion
(globbing); and quote removal.
$ set -x
$ echo ~/{a,b}.txt $((2 + 3)) "$(date +%Y)"
++ date +%Y
+ echo /home/jano/a.txt /home/jano/b.txt 5 2026
/home/jano/a.txt /home/jano/b.txt 5 2026
$ set +x
+ set +x
Brace expansion
Brace expansion generates strings from a comma-separated list or a range. It is purely textual and does not look at files.
echo file{1,2,3}.txt
echo {a,b}{1,2}
echo /etc/{passwd,group,hosts}
mkdir -p project/{src,tests,docs}
ls project
cp glob/notes.txt glob/notes.txt.bak
cp glob/notes.txt{,.orig}
ls glob/notes.txt*
echo nosuch{1,2}.txt
A prefix and suffix are attached to each item, and several braces
combine into all pairs. file{,.orig} expands to
file file.orig, a short way to make a backup copy. Unlike
globs, braces produce names whether or not the files exist. For ranges
such as {1..10}, see the Bash
loops article.
$ echo file{1,2,3}.txt
file1.txt file2.txt file3.txt
$ echo {a,b}{1,2}
a1 a2 b1 b2
$ echo /etc/{passwd,group,hosts}
/etc/passwd /etc/group /etc/hosts
$ mkdir -p project/{src,tests,docs}
$ ls project
docs
src
tests
$ cp glob/notes.txt glob/notes.txt.bak
$ cp glob/notes.txt{,.orig}
$ ls glob/notes.txt*
glob/notes.txt
glob/notes.txt.bak
glob/notes.txt.orig
$ echo nosuch{1,2}.txt
nosuch1.txt nosuch2.txt
Tilde expansion
A tilde at the start of a word expands to a home directory.
echo ~ echo ~root cd /tmp; cd /etc echo ~+ ~- echo "~"
~ is the current user's home, ~user another
user's home. ~+ is the current directory and
~- the previous one. The tilde is not expanded inside
quotes, so use "$HOME/file" rather than
"~/file" in quoted strings.
$ echo ~ /home/jano $ echo ~root /root $ cd /tmp; cd /etc $ echo ~+ ~- /etc /tmp $ echo "~" ~
Default values
Parameter expansion ${...} can substitute a default for
unset or empty variables.
unset name; empty=""
echo "${name:-guest}"
echo "${empty:-guest}"
echo "${empty-guest}"
echo "${name:=guest}"; echo "$name"
echo "${name:+set}"
echo "${missing:?is required}"
${var:-default} uses the default if the variable is unset or
empty; without the colon, only if it is unset. := also
assigns the default to the variable. :+ gives the
alternative value only when the variable is set and non-empty.
:? prints an error and, in a script, exits; it is a compact
way to require variables.
$ unset name; empty=""
$ echo "${name:-guest}"
guest
$ echo "${empty:-guest}"
guest
$ echo "${empty-guest}"
$ echo "${name:=guest}"; echo "$name"
guest
guest
$ echo "${name:+set}"
set
$ echo "${missing:?is required}"
bash: missing: is required
Length and substrings
${#var} is the length of a value, and
${var:offset:length} a part of it.
s="Hello, World"
echo "${#s}"
echo "${s:0:5}"
echo "${s:7}"
echo "${s: -5}"
echo "${s:(-5):3}"
word="žltý kôň"
echo "${#word}"
Offsets start at 0. A negative offset counts from the end; it needs a
space or parentheses, because ${s:-5} would be the default
value syntax. In a UTF-8 locale, lengths and offsets count characters,
not bytes: žltý kôň has 8 characters.
$ s="Hello, World"
$ echo "${#s}"
12
$ echo "${s:0:5}"
Hello
$ echo "${s:7}"
World
$ echo "${s: -5}"
World
$ echo "${s:(-5):3}"
Wor
$ word="žltý kôň"
$ echo "${#word}"
8
Removing prefixes and suffixes
Four operators remove a pattern from the start or end of a value. They
replace many uses of basename, dirname, and
sed.
path="/var/log/nginx/access.log.gz"
echo "${path##*/}"
echo "${path%/*}"
file="${path##*/}"
echo "${file%.*}"
echo "${file%%.*}"
echo "${file#*.}"
echo "${file##*.}"
# removes from the start and % from the end; a
single character removes the shortest match, a double one the longest.
So ${path##*/} is the file name and ${path%/*}
the directory. ${file%.*} removes the last extension,
${file%%.*} all of them, and ${file##*.} keeps
only the last extension.
$ path="/var/log/nginx/access.log.gz"
$ echo "${path##*/}"
access.log.gz
$ echo "${path%/*}"
/var/log/nginx
$ file="${path##*/}"
$ echo "${file%.*}"
access.log
$ echo "${file%%.*}"
access
$ echo "${file#*.}"
log.gz
$ echo "${file##*.}"
gz
Search and replace
${var/pattern/replacement} replaces the first match;
// replaces all of them.
s="one two two three"
echo "${s/two/2}"
echo "${s//two/2}"
echo "${s// /_}"
echo "${s/#one/1}"
echo "${s/%three/3}"
for f in "my holiday photo.JPG" "Old Notes.TXT"; do echo "${f// /_}"; done
/# anchors the pattern at the start and /% at
the end. Patterns are globs, not regular expressions. Replacing spaces
with underscores is a typical use when renaming files.
$ s="one two two three"
$ echo "${s/two/2}"
one 2 two three
$ echo "${s//two/2}"
one 2 2 three
$ echo "${s// /_}"
one_two_two_three
$ echo "${s/#one/1}"
1 two two three
$ echo "${s/%three/3}"
one two two 3
$ for f in "my holiday photo.JPG" "Old Notes.TXT"; do echo "${f// /_}"; done
my_holiday_photo.JPG
Old_Notes.TXT
Changing case
^ converts to uppercase and , to lowercase;
doubled, they apply to all characters.
name="jan bodnar"
echo "${name^}"
echo "${name^^}"
lang="SLOVAK"
echo "${lang,,}"
echo "${lang,}"
The single forms change only the first character. Converting to one case is useful before comparing user input.
$ name="jan bodnar"
$ echo "${name^}"
Jan bodnar
$ echo "${name^^}"
JAN BODNAR
$ lang="SLOVAK"
$ echo "${lang,,}"
slovak
$ echo "${lang,}"
sLOVAK
Indirect expansion
${!var} uses the value of var as the name of
another variable, and ${!prefix@} lists variable names.
APP_PORT=8080; APP_HOST=localhost; APP_DEBUG=1
var=APP_PORT
echo "${!var}"
echo "${!APP_@}"
for v in "${!APP_@}"; do echo "$v=${!v}"; done
Listing the variables with a common prefix is handy for printing a configuration. For more complex data, associative arrays are clearer than indirect names.
$ APP_PORT=8080; APP_HOST=localhost; APP_DEBUG=1
$ var=APP_PORT
$ echo "${!var}"
8080
$ echo "${!APP_@}"
APP_DEBUG APP_HOST APP_PORT
$ for v in "${!APP_@}"; do echo "$v=${!v}"; done
APP_DEBUG=1
APP_HOST=localhost
APP_PORT=8080
Command substitution
$(command) is replaced by the output of the command.
today=$(date +%F) echo "Report for $today" echo "Files: $(ls glob | wc -l)" echo "Kernel: `uname -r`" echo "Dir of this file: $(basename "$(dirname "$PWD/glob/src/main.c")")" lines=$(printf 'a\nb\n\n\n'); echo "[$lines]"
The older backtick form does the same, but $( ) nests
without escaping and is easier to read. Quotes inside
$( ) are independent of the quotes around it. Command
substitution removes all trailing newlines from the output.
$ today=$(date +%F) $ echo "Report for $today" Report for 2026-10-24 $ echo "Files: $(ls glob | wc -l)" Files: 12 $ echo "Kernel: `uname -r`" Kernel: 6.8.0-138-generic $ echo "Dir of this file: $(basename "$(dirname "$PWD/glob/src/main.c")")" Dir of this file: src $ lines=$(printf 'a\nb\n\n\n'); echo "[$lines]" [a b]
Arithmetic expansion
$(( expression )) is replaced by the result of an integer
calculation.
echo $(( 7 + 3 * 2 ))
echo $(( 7 / 2 )) $(( 7 % 2 )) $(( 2 ** 10 ))
a=5; b=3
echo $(( a * b ))
echo $(( 0xff )) $(( 2#1010 )) $(( 8#17 ))
echo $(( 1 / 0 ))
echo $(( 10 / 3 * 3 ))
awk 'BEGIN { printf "%.2f\n", 10 / 3 }'
The usual precedence applies, / is integer division, and
** is exponentiation. Numbers can be written in hexadecimal
or with a base prefix, base#digits. Integer division loses
the remainder, so 10 / 3 * 3 is 9. Bash has no
floating-point numbers; awk or bc handle
decimals.
$ echo $(( 7 + 3 * 2 ))
13
$ echo $(( 7 / 2 )) $(( 7 % 2 )) $(( 2 ** 10 ))
3 1 1024
$ a=5; b=3
$ echo $(( a * b ))
15
$ echo $(( 0xff )) $(( 2#1010 )) $(( 8#17 ))
255 10 15
$ echo $(( 1 / 0 ))
bash: 1 / 0 : division by 0 (error token is "0 ")
$ echo $(( 10 / 3 * 3 ))
9
$ awk 'BEGIN { printf "%.2f\n", 10 / 3 }'
3.33
Word splitting
The results of unquoted variable expansion and command substitution are
split into words at the characters in IFS (by default
space, tab, and newline).
names="Peter Lucia Martin"
printf '[%s]\n' $names
printf '[%s]\n' "$names"
csv="red,green,blue"
IFS=, read -ra colors <<< "$csv"
printf '[%s]\n' "${colors[@]}"
printf repeats its format for each argument, which makes
the words visible. Unquoted, the value became three words and the
repeated spaces disappeared; quoted, it stayed one word. To split a
string on purpose, read -a with a custom IFS
puts the parts into an array. See the
Bash quoting article.
$ names="Peter Lucia Martin"
$ printf '[%s]\n' $names
[Peter]
[Lucia]
[Martin]
$ printf '[%s]\n' "$names"
[Peter Lucia Martin]
$ csv="red,green,blue"
$ IFS=, read -ra colors <<< "$csv"
$ printf '[%s]\n' "${colors[@]}"
[red]
[green]
[blue]
Globbing basics
Pathname expansion, or globbing, replaces words that contain
*, ?, or [ with the matching file
names, sorted.
cd glob ls echo *.txt echo data?.csv echo data[12].csv echo data[!1]*.csv echo [[:upper:]]* echo * echo .*
* matches any string, ? exactly one character,
[12] one of the listed characters, and [!1]
(or [^1]) any character except those listed. Character
classes such as [[:upper:]] and [[:digit:]]
work too. A * does not match names that start with a dot;
hidden files need an explicit .*. The names are sorted
according to the locale, which is why data10.csv comes
before data1.csv.
$ cd glob $ ls data10.csv data1.csv data2.csv docs image.PNG notes.txt notes.txt.bak notes.txt.orig photo.png README.md report.txt src $ echo *.txt notes.txt report.txt $ echo data?.csv data1.csv data2.csv $ echo data[12].csv data1.csv data2.csv $ echo data[!1]*.csv data2.csv $ echo [[:upper:]]* README.md $ echo * data10.csv data1.csv data2.csv docs image.PNG notes.txt notes.txt.bak notes.txt.orig photo.png README.md report.txt src $ echo .* .env .hidden
Patterns without matches
If a pattern matches nothing, Bash passes it unchanged to the command.
echo *.xml ls *.xml shopt -s nullglob; echo *.xml; shopt -u nullglob shopt -s failglob echo *.xml shopt -u failglob
ls then complains about a file literally named
*.xml. With nullglob, a pattern without matches
expands to nothing, and with failglob, Bash reports an
error and does not run the command. nullglob is useful in
loops over files; be careful with commands such as ls,
which list the current directory when they get no arguments.
$ echo *.xml *.xml $ ls *.xml ls: cannot access '*.xml': No such file or directory $ shopt -s nullglob; echo *.xml; shopt -u nullglob $ shopt -s failglob $ echo *.xml bash: no match: *.xml $ shopt -u failglob
Glob options
Further shopt options change how patterns match.
echo *.png shopt -s nocaseglob; echo *.png; shopt -u nocaseglob shopt -s dotglob; echo *; shopt -u dotglob echo **/*.c shopt -s globstar; echo **/*.c; shopt -u globstar
nocaseglob ignores case, so image.PNG matches
too. dotglob makes * include hidden files.
With globstar, ** matches any number of
directories, here finding C files at all levels; without it,
** behaves like *.
$ echo *.png photo.png $ shopt -s nocaseglob; echo *.png; shopt -u nocaseglob image.PNG photo.png $ shopt -s dotglob; echo *; shopt -u dotglob data10.csv data1.csv data2.csv docs .env .hidden image.PNG notes.txt notes.txt.bak notes.txt.orig photo.png README.md report.txt src $ echo **/*.c src/main.c src/util.c $ shopt -s globstar; echo **/*.c; shopt -u globstar src/lib/list.c src/main.c src/util.c
Extended globs
The extglob option adds pattern operators similar to
regular expressions.
shopt extglob shopt -s extglob echo !(*.csv|*.md) echo data+([0-9]).csv echo @(report|notes).txt echo data?([0-9])1.csv
!(...) matches anything except the patterns,
+(...) one or more occurrences, @(...) exactly
one of the alternatives, ?(...) zero or one, and
*(...) zero or more. extglob is off in scripts;
in interactive shells, Debian's bash-completion turns it on. Because it
changes how lines are parsed, enable it on a line before the patterns
are used.
$ shopt extglob extglob off $ shopt -s extglob $ echo !(*.csv|*.md) docs image.PNG notes.txt notes.txt.bak notes.txt.orig photo.png report.txt src $ echo data+([0-9]).csv data10.csv data1.csv data2.csv $ echo @(report|notes).txt notes.txt report.txt $ echo data?([0-9])1.csv data1.csv
Quoted patterns
Quotes prevent globbing. This matters when a pattern is meant for a command rather than the shell.
pattern="*.csv" echo $pattern echo "$pattern" find . -name *.md find . -name '*.md'
A pattern stored in a variable is expanded when the variable is used
unquoted. With find, the unquoted *.md was
expanded by the shell to README.md before
find ran, so find searched only for that name
and missed docs/guide.md. Quoted, the pattern reaches
find, which matches it in every directory.
$ pattern="*.csv" $ echo $pattern data10.csv data1.csv data2.csv $ echo "$pattern" *.csv $ find . -name *.md ./README.md $ find . -name '*.md' ./README.md ./docs/guide.md
Accidental globbing
Any unquoted expansion that contains a glob character is subject to globbing, even in text that has nothing to do with files.
msg="Warning: * not allowed" echo $msg echo "$msg" set -f echo $msg set +f
The * in the message was replaced by the directory listing.
Quoting fixes it. set -f disables globbing entirely, which
some scripts do when they never need it.
$ msg="Warning: * not allowed" $ echo $msg Warning: data10.csv data1.csv data2.csv docs image.PNG notes.txt notes.txt.bak notes.txt.orig photo.png README.md report.txt src not allowed $ echo "$msg" Warning: * not allowed $ set -f $ echo $msg Warning: * not allowed $ set +f
The order matters
Because of the order of expansions, some combinations work and others do not.
ext=txt
echo *.$ext
dir=src
echo $dir/*.c
start=1; end=3
echo {$start..$end}
eval echo "{$start..$end}"
Variables are expanded before globbing, so patterns built from variables
work. Brace expansion comes first of all, when $start and
$end are still text, so {$start..$end} is not a
valid range. eval would expand the line twice, but it also
runs any code hidden in the variables; prefer seq or a
C-style loop.
$ ext=txt
$ echo *.$ext
notes.txt report.txt
$ dir=src
$ echo $dir/*.c
src/main.c src/util.c
$ start=1; end=3
$ echo {$start..$end}
{1..3}
$ eval echo "{$start..$end}"
1 2 3
Parameter expansion summary
| Expansion | Result |
|---|---|
${var:-default} | Default if unset or empty |
${var:=default} | Default, also assigned |
${var:?message} | Error if unset or empty |
${var:+alt} | Alternative if set and non-empty |
${#var} | Length |
${var:offset:length} | Substring |
${var#pat}, ${var##pat} | Remove shortest, longest prefix |
${var%pat}, ${var%%pat} | Remove shortest, longest suffix |
${var/pat/rep}, ${var//pat/rep} | Replace first, all matches |
${var^^}, ${var,,} | Uppercase, lowercase |
${!var} | Indirect expansion |
Best practices
- Quote expansions: Write
"$var"and"$(command)"unless you want splitting and globbing. - Quote patterns meant for programs: For
find,grep, and others. - Use parameter expansion for file names: It is
faster than calling
basenameorsed. - Handle globs without matches: Use
nullglobor test the result. - Avoid eval: There is almost always a safer way.
- Debug with set -x: It shows what the command really received.
Source
Bash manual: Shell Expansions, Bash manual: Pattern Matching
In this article, we have looked at the order of the shell's expansions, used brace, tilde, parameter, command, and arithmetic expansion, seen how word splitting works, and matched files with globs, glob options, and extended patterns. See also the Bash quoting, Bash loops, and environment variables articles.
Author
List all Linux tutorials.