Bash Parameter Expansion with Cheat Sheet

Last updated: February 22, 2023 | Linuxopsys

Any number or string value or list of values (numeric or associative array) can be stored using a variable in bash. You can define variables in bash without using the `declare` command or by using the `declare` command where the data type is declared at the time of declaration. Bash parameter expansion or parameter expansion is defined by the ‘$’ symbol and the optional curly brackets ({ }). The parameter expansion is used with the curly brackets when it is required to read or modify the original parameter value. You have to use double quotes (“) when expanding values by using parameter expansion.

The way of using parameter expansion in bash has been explained in this tutorial. 

What is parameter expansion? 

The value of a shell variable can be read, expanded, replaced, or modified based on the particular syntax by using bash parameter expansion. The syntax of parameter expansion is given below.

Syntax:

${variable}  

Difference between parameter expansion and parameter substitution

Parameter ExpansionParameter Substitution
It is used to extract the value of a variableIt is used to substitute the value of a variable
The default value can be set to the variable if the variable is undefined.No default value can be set if the parameter is undefined.
Example:

#Print the default value in the terminal if the variable is not defined before
echo "${language:-Bash} Programming"
Example:

#Define the variable
language="Bash"
#Print the defined value in the terminal
echo "${language} Programming"

Basic parameter expansion: accessing and setting variable values 

Different ways of using bash parameter expansion have been explained in this section.

Conditional expressions with parameter expansion 

Many conditional bash parameter expansions can be used to check whether the variable is defined or empty. Some uses of conditional expressions with bash parameter expansion have been shown in this section.

Use of ‘:-’:

The use of ‘:-’ in the parameter expansion has been shown in the following script.

#Unset the variable and check the output for the ':-' expansion
unset var
echo ${var:-Scripting Language}
echo $var
#Set the variable and check the output for the ':-' expansion
var="Bash"
echo ${var:-Scripting Language}
echo $var
Conditional expressions using :-

The default value has been printed in the terminal but not stored in the variable when the $var was undefined. The defined value of the variable has been printed in the terminal when the $var was defined.  

Use of ‘:+’:

The use of ‘:+’ in the parameter expansion has been shown in the following script. 

#Unset the variable and check the output for the ':+' expansion
unset var
echo ${var:+Scripting Language}
echo $var
#Set the variable and check the output for the ':+' expansion
var="Bash"
echo ${var:+Scripting Language}
echo $var
Conditional expressions using +

The default value was not printed in the terminal and not stored in the $var when the variable was undefined. The default value was printed in the terminal and not stored in the $var when the variable was defined.

Use of ‘:=’:

The use of ‘:=’ in the parameter expansion has been shown in the following script. 

#Unset the variable and check the output for ':=' expansion
unset var
echo ${var:=Scripting Language}
echo $var
#Set the variable and check the output for ':=' expansion
var="Bash"
echo ${var:=Scripting Language}
echo $var
Conditional expressions using =

The default value has been printed in the terminal and stored in the $var also when the variable was undefined. The default value was not printed in the terminal and was not stored in the $var when the variable was defined. 

Substring by bash parameter expansion 

You can retrieve the part of a string by using parameter expansion. The way of getting different substrings from a string value by using parameter expansion has been shown in the following script. The first parameter expansion will cut a substring of 4 characters starting from position 0. The second parameter expansion will cut a substring of 9 characters starting from position 5. The starting position of the substring has been given in the third parameter expansion but the length of the substring was not given. So, the remaining part of the string from the starting position will be retrieved for the last parameter expansion.

#Define a string variable
var="Bash Parameter Expansion"
#Substring of 4 characters starting from position 0
echo "First word: ${var:0:4}"
#Substring of 9 characters starting from position 5
echo "Second word: ${var:5:9}"
#Substring starting from position 15  
echo "Third word: ${var:15}"
Substring

The string value, ‘Bash’ has been retrieved as the first substring. The string value, ‘Parameter’ has been retrieved as the second substring. The string value, ‘Expansion’ has been retrieved as the third substring.

Substitute with bash parameter expansion 

The value of the variable is substituted in a case-sensitive manner by using parameter expansion. The way of replacing the first occurrence and all occurrences of the searching word in a string by using parameter expansion has been shown in the following script.

#Define the first variable
var1="The color of the dress is red"
#Substitute the single matching value
echo "${var1/red/blue}"
#Define the second variable
var2="eat to live not live to eat"
#Substitute all matching values
echo "${var2//eat/Eat}"

The word, ‘red’ has been searched and replaced by the word, ‘blue’ in the output of the first parameter expansion. All occurrences of the word, ‘eat’ has been searched and replaced by the word, ‘Eat’ in the output of the second parameter expansion. 

Regex with bash parameter expansion 

Different types of regular expression patterns can be used in the parameter expansion to remove a particular part of a string. A very simple use of regex with bash parameter expansion has been shown in the following script. According to the pattern, the numeric part will be removed from the end of the string. 

#Define a variable
var="The price of the book is $50"
#Remove the part of the string using regex
echo "${var/%[0-9]}\$75"
regex

‘$50’ has been removed from the $var and $75 has been added at the end of the $var value.

Split with bash parameter expansion

Add the following script in a bash file that shows the use of the parameter expansion to split a string value based on a separator. Here, the colon(:) has been used as the separator value. After splitting, the values will be stored in an array and the array values will be parsed by using parameter expansion and a loop. 

#!/bin/bash
#Define a string variable
course="Code-CSE206:Name-Java2:Credit-2.0"
#Split the string into an array based on the colon(:)
course_info=(${course//:/ })
#Read the array by using parameter expansion
for val in "${course_info[@]}" 
do
split

The string value, "Code-CSE206:Name-Java2:Credit-2.0" has been divided into three parts based on the colon(:). These are ‘Code-CSE206’, ‘Name-Java2’, and ‘Credit-2.0’. These values have been printed in the output.

Bash parameter expansion cheat sheet

The cheat sheet of bash parameter expansion has been given shortly in this section. The cheat sheet has been categorized into different parts.

Use of basic parameterIndirection
#Print parameter value
echo  "${parameter}"
#Print the parameter value with another string value
echo  "${parameter} World"
#Assign a parameter value
food="burger"
#Assign another parameter by referencing another parameter
parameter="food"
#Print the parameter value by indirection
echo "My favorite ${parameter} is ${!parameter}."
Use of default valueCount the length of the parameter
#Assign default value to the parameter and print in the terminal if the parameter is unset
echo  "${parameter:=Good}"
#Print default value in the terminal if the variable is unset
echo  "${parameter:-Better}"
#Print the default value in the terminal if the variable is set
echo  "${parameter:+Best}"
#Print the length of the parameter value
echo  "${#parameter}"
#Print the length of the array
echo  "${#parameter[@]}"
#Print length of the 5th element of the array
echo  "${#parameter[5]}"
Generate substringSearch and Replace
#Cut the substring from the left position(5) counting from 0 to the remaining part of the string.
echo "${parameter:5}"
#Cut the substring of 5 characters from the left position(3) counting from 0.
echo "${parameter:3:5}"
#Cut the substring from the right position(2) counting from 1 to the remaining part of the string.
echo "${parameter:-2}"
#Cut the substring of 2 characters from the right position(4) counting from 1.
echo "${parameter:-4:2}"
#Search and replace the first occurrence of the searching string
echo ${parameter/search/replace}
#Search and replace all occurrences of the searching string
echo ${parameter//search/replace}
#Search and replace the first occurrence of the searching string if it exists at the beginning of the string
echo ${parameter/#search/replace}
#Search and replace the first occurrence of the searching string if it exists at the end of the string
echo ${parameter/%search/replace}

Conclusion

Bash parameter expansion is a very useful feature of bash programming. The tutorial will help you to learn the different uses of bash parameter expansion to modify the parameter value in the bash script.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment