Hemanth's Scribes
python

Why Parameter Expansion in Bash?

Author Photo

Hemanth HM

· 1 min read · .md

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%%/} ${FILE%/} /usr/local/labs/python ~~

But, why parameter expansion?

“

Let’s time using cut.

music=wow.mp3 TIMEFORMAT=‘real: %E’ time for ((i=0; i<1000; i++)); do

      n=$(cut -d . -f 1 <<<"$x"); 

done > /dev/null

real: 2.758

Now P.E

music=wow.mp3 TIMEFORMAT=‘real: %E’; time for ((i=0; i<1000; i++)); do

      n=${x%%.*}; 

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 ;)

#python#bash
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.

100%