🔥 Understanding Bash Parameter Expansion (With Real Terminal Output)
In this post, we will explore powerful Bash parameter expansion features using real terminal examples, it helps to manipulate variables without calling external commands like sed, cut, awk etc.
1️⃣ Basic Variable Expansion
All three produce the same output.
❓ What is the advantage of putting {} and double quotes?
Without Quotes
Becomes internally:
Bash sees two separate words because of the space.
With Quotes
Becomes internally:
Now Bash sees one single string.
With echo we don't notice much difference.
So let’s try something practical.
2️⃣ Creating Directory — Real Difference
Without Quotes
Two directories were created because Bash split the variable at space.
With Quotes
Now only one directory is created.
✅ Always quote variables if they may contain spaces.
3️⃣ Get Length of a String
To get the length, use # inside parameter expansion:
# returns the length of the variable.
4️⃣ Capitalization Operations
Reset value
🔹 Capitalize First Letter
🔹 Capitalize All Letters
🔹 Capitalize Specific Letter
🔹 Capitalize Specific Pattern
5️⃣ Lowercase Operations
Reset value
🔹 Lowercase All Letters
🔹 Lowercase First Letter
🔹 Lowercase Specific Letter
6️⃣ Default Values for Positional Parameters
Script: pos-def.sh
With Argument
Without Argument
name=$1 is simple assignment.
But:
Means:
Take argument 1. If empty or not set, use "Mahesh".
Using Variable Expansion as Default
7️⃣ Mandatory Parameter Check
If your script must not run without an argument:
Custom Error Message
Even empty string fails:
8️⃣ String Replacement
Using External Command
Using Parameter Expansion (First Occurrence)
Replace All Occurrences
Replace Pattern
9️⃣ dirname / basename Equivalent
Remove From Start
Remove Longest From Start
Remove From End (Suffix Removal)
How Bash processes it:
Original: /home/oracle/foo.txt
Search from right → find /foo.txt
Remove it → Result /home/oracle
| Operator | Direction | Match Size | Result for /home/oracle/foo.txt |
${path#*/} | Left $\rightarrow$ | Shortest | home/oracle/foo.txt |
${path##*/} | Left $\rightarrow$ | Longest | foo.txt (Basename) |
${path%/*} | $\leftarrow$ Right | Shortest | /home/oracle (Dirname) |
${path%%/*} | $\leftarrow$ Right | Longest | (empty) |
🔟 Substring Using Parameter Expansion
With Length
From Backward (Negative Index)
⚠ Important: There must be a space before -2.