~4 min read • Updated Jul 18, 2025

1. What Is Expansion in Bash?


Expansion is the process Bash uses to analyze and transform parts of a command before executing it. For example:


echo this is a test

prints this is a test literally, while:


echo *

expands * to match filenames in the current directory.


2. Pathname Expansion


Wildcard patterns expand to matching filenames:



echo D*               # Files starting with D
echo *s               # Files ending with s
echo [[:upper:]]*     # Files starting with uppercase letters
echo /usr/*/share     # Directories in /usr containing 'share'

Hidden Files:



echo .*               # Matches ., .., and hidden files
echo .[!.]*           # Skips . and .. for safer hidden file listing
ls -A                 # Lists hidden files (excluding . and ..)

3. Tilde Expansion (~)



echo ~               # Expands to current user’s home directory
echo ~username       # Expands to another user's home

4. Arithmetic Expansion


OperatorDescription
+Addition
-Subtraction
*Multiplication
/Integer Division
%Modulo
**Exponentiation


echo $((2 + 2))                   # 4
echo $(((5**2) * 3))             # 75
echo $((5 / 2))                  # 2
echo $((5 % 2))                  # 1

5. Brace Expansion



echo Front-{A,B,C}-Back           # Front-A-Back ...
echo {1..5}                       # 1 2 3 4 5
echo {01..15}                     # 01 02 ... 15
echo {Z..A}                       # Z Y ... A
echo a{A{1,2},B{3,4}}b            # aA1b aA2b aB3b aB4b

mkdir Photos
cd Photos
mkdir {2007..2009}-{01..12}      # Generates year/month folders

6. Parameter Expansion ($VARIABLE)



echo $USER           # Current username
echo $SUER           # Undefined → empty string
printenv | less      # All environment variables

7. Command Substitution ($(command))



echo $(ls)                              # File list as echo args
ls -l $(which cp)                      # Info for cp binary
file $(ls -d /usr/bin/* | grep zip)    # Inspect zip-related files

Backtick syntax \`command\` is supported but less preferred.


8. Quoting Mechanisms


TypeBehavior
NoneAll expansions applied, with word splitting
"Double quotes"Suppress pathname/brace expansion; allow parameter and command substitution
'Single quotes'Suppress all expansions

Examples:



echo "$USER $((2+2)) $(cal)"       # Preserves formatting
echo 'text ~/*.txt {a,b} $(echo foo)'  # Output exactly as typed
ls -l "two words.txt"
mv "two words.txt" two_words.txt

9. Escaping Characters with Backslash


Use \ to prevent special character behavior:



echo "User balance: \$5.00"
mv bad\&filename good_filename
echo "Backslash: \\"

10. Control Characters (Escape Sequences)


SequenceMeaning
\aBell (alert beep)
\bBackspace
\nNewline
\rCarriage return

Written & researched by Dr. Shahin Siami