~2 min read • Updated Jul 18, 2025
Bash expansions allow the shell to replace specific characters and patterns with actual values before command execution. Users can handle files, variables, arithmetic, and command output dynamically, while quoting controls how text and symbols are interpreted. This guide explores these powerful features step by step.
Pathname Expansion (*, ?, [])
echo *Displays all files in the current directory.
echo D*Lists all files starting with 'D'.
Handling Hidden Files
echo .[!.]*Matches hidden files excluding . and ... Alternatively:
ls -ATilde Expansion (~)
echo ~Expands to the current user’s home directory.
echo ~usernameExpands to another user’s home directory.
Arithmetic Expansion
echo $((2 + 2))Performs basic calculations.
echo $(((5**2) * 3))Exponentiation and multiplication result: 75
Brace Expansion
echo Front-{A,B,C}-BackOutput: Front-A-Back Front-B-Back Front-C-Back
Sequences and Bulk Creation
echo Number_{01..05}mkdir {2007..2009}-{01..12}Creates year-month folders.
Parameter Expansion ($VAR)
echo $USERDisplays the username.
printenv | lessLists environment variables.
Command Substitution
echo $(ls)Injects command output into another command.
ls -l $(which cp)Displays details about cp.
file $(ls -d /usr/bin/* | grep zip)Quoting Techniques
Without Quotes
echo text ~/*.txt {a,b} $(echo foo) $((2+2)) $USERDouble Quotes
echo "text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER"Suppresses pathname and brace expansion; preserves others.
Single Quotes
echo 'text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER'Suppresses all expansions.
Escaping Characters
echo "The balance is: \$5.00"Prevents incorrect variable expansion like $5.
Escaping Special Characters
mv bad\&filename good_filenameecho "Backslash: \\"Control Characters with Escape Sequences
| Sequence | Meaning |
|---|---|
| \a | Bell sound (beep) |
| \n | Newline |
| \t | Tab |
| \r | Carriage return |
| \b | Backspace |
Usage in echo
echo -e "Time's up\a"echo $'\a'Conclusion
Bash expansion and quoting provide foundational tools for efficient scripting and command execution. By understanding how variables, commands, patterns, and special characters are interpreted, users can write smarter scripts, debug outputs effectively, and control shell behavior with precision.
Written & researched by Dr. Shahin Siami