Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • What is parameter expansion?
  • Basic parameter expansion: accessing and setting variable values
  • Bash parameter expansion cheat sheet

Bash Parameter Expansion with Cheat Sheet

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 Expansion
Parameter Substitution

It is used to extract the value of a variable

It 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 ':-' expansionunset varecho ${var:-Scripting Language}echo $var#Set the variable and check the output for the ':-' expansionvar="Bash"echo ${var:-Scripting Language}echo $var

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 ':+' expansionunset varecho ${var:+Scripting Language}echo $var#Set the variable and check the output for the ':+' expansionvar="Bash"echo ${var:+Scripting Language}echo $var

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 ':=' expansionunset varecho ${var:=Scripting Language}echo $var#Set the variable and check the output for ':=' expansionvar="Bash"echo ${var:=Scripting Language}echo $var

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 variablevar="Bash Parameter Expansion"#Substring of 4 characters starting from position 0echo "First word: ${var:0:4}"#Substring of 9 characters starting from position 5echo "Second word: ${var:5:9}"#Substring starting from position 15 echo "Third word: ${var:15}"

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 variablevar1="The color of the dress is red"#Substitute the single matching valueecho "${var1/red/blue}"#Define the second variablevar2="eat to live not live to eat"#Substitute all matching valuesecho "${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 variablevar="The price of the book is $50"#Remove the part of the string using regexecho "${var/%[0-9]}\$75"

‘$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 variablecourse="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 expansionfor val in "${course_info[@]}"do

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 parameter

Indirection

#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 value

Count 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 substring

Search 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}

PreviousHow to Do Bash Variable Substitution (Parameter Substitution)NextBash getopts with Examples

Last updated 1 year ago

regex
Conditional expressions using +
Conditional expressions using :-
Substring
Conditional expressions using =
split