Why parameter expansion in bash?

Most of us would have come across bash scripts that have the use of secondary commands for simple string manipulations, such as cut and awk , but wonders can be done with parameter expansion in bash at very effective and efficient manner.

Even before diving into the why parameter expansion it's a must to know how it works!

Checkout the below examples to see how parameter expansion works :

${NAME}       com.example.old.java
${NAME#*.}           example.old.java
${NAME##*.}                         java
${NAME%%.*}  com
${NAME%.*}    com.example.old
${FILE}          /usr/local/labs/python.py
${FILE#*/}     usr/local/labs/python.py
${FILE##*/}                           python.py
${FILE%/*}    /usr/local/labs/python

But, why parameter expansion?

# Let's time using cut.
time for ((i=0; i<1000; i++)); do 
          n=$(cut -d . -f 1 <<<"$x"); 
done > /dev/null
# real: 2.758
# Now P.E
TIMEFORMAT='real: %E'; 
time for ((i=0; i<1000; i++)); do 
done > /dev/null
# real: 0.022 

Mind blowing! 2.756 vs 0.022, the code has done the talking! :)

P.S : thanks to e36freak for TIMEFORMAT hack and greycat logic "%" is towards the right in a US keyboard layout and "#" is towdars the left ;)

Share this