A parameter is something that stores value and is reference by a name. This are also known as bash variable or simply variables.
Often we’d like to get values from the parameters, this procedure is called parameter expansion.
The most common usage to get the value of a parameter is to reference it by a “$” symbol.
For example,
srvstva@x3400-m3:~$ name="Ankur" srvstva@x3400-m3:~$ echo $name Ankur Or, srvstva@x3400-m3:~$ echo ${name} Ankur
But there are many other tricks that can be quite helpful.
Case modification
${VARIABLE^} – converts the first character to upper case
srvstva@x3400-m3:~$ name="ankur" srvstva@x3400-m3:~$ echo ${name^} Ankur
${VARIABLE^^} – converts the whole string to upper case
srvstva@x3400-m3:~$ name="ankur" srvstva@x3400-m3:~$ echo ${name^^} ANKUR
${VARIABLE,} – converts the first character to lower case
srvstva@x3400-m3:~$ name=ANKUR srvstva@x3400-m3:~$ echo ${name,} aNKUR
${VARIABLE,,} – converts the whole string to lower case
srvstva@x3400-m3:~$ name=ANKUR srvstva@x3400-m3:~$ echo ${name,,} ankur
Variable name expansion
Variables can be expanded to print their own names. In the preceding example, the variable name contained the string “ANKUR”
Now lets see how expansion works for this cases. A trailing “!” and a leading “*” or “@” does the trick.
srvstva@x3400-m3:~$ name="ANKUR" srvstva@x3400-m3:~$ echo ${!name*} name srvstva@x3400-m3:~$ echo ${!name@} name
String length
You can easily find the length of string using this ${#VARIABLE}
srvstva@x3400-m3:~$ name="ANKUR" srvstva@x3400-m3:~$ echo ${#name} 5
Finding substrings
Its as easy as making a cup of coffee 😉 Just look at the examples to understand
${VARIABLE:Offset} Or ${VARIABLE:Offset:Length}
srvstva@x3400-m3:~$ name="ANKUR" srvstva@x3400-m3:~$ echo ${name:2} KUR srvstva@x3400-m3:~$ echo ${name:2:2} KU srvstva@x3400-m3:~$ echo ${name:1:4} NKUR srvstva@x3400-m3:~$ echo ${name:0} ANKUR
Search and replace
Searching and replacing can done using following ways.
${VARIABLE/PATTERN/STRING_TO_REPLACE} – Replace the pattern with the string
${VARIABLE/PATTERN} – Print all minus the pattern
srvstva@x3400-m3:~$ name="ANKUR" srvstva@x3400-m3:~$ echo ${name/NK/nk} AnkUR srvstva@x3400-m3:~$ echo ${name/NK} AUR
Hope you enjoyed the simple bash tricks.
Happy copying & pasting!