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.
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'
echo .* # Matches ., .., and hidden files
echo .[!.]* # Skips . and .. for safer hidden file listing
ls -A # Lists hidden files (excluding . and ..)
echo ~ # Expands to current user’s home directory
echo ~username # Expands to another user's home
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Integer Division |
% | Modulo |
** | Exponentiation |
echo $((2 + 2)) # 4
echo $(((5**2) * 3)) # 75
echo $((5 / 2)) # 2
echo $((5 % 2)) # 1
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
echo $USER # Current username
echo $SUER # Undefined → empty string
printenv | less # All environment variables
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.
Type | Behavior |
---|---|
None | All expansions applied, with word splitting |
"Double quotes" | Suppress pathname/brace expansion; allow parameter and command substitution |
'Single quotes' | Suppress all expansions |
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
Use \
to prevent special character behavior:
echo "User balance: \$5.00"
mv bad\&filename good_filename
echo "Backslash: \\"
Sequence | Meaning |
---|---|
\a | Bell (alert beep) |
\b | Backspace |
\n | Newline |
\r | Carriage return |