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
  • Declaring variables in bash
  • What is variable substitution in bash?
  • Conclusion

How to Do Bash Variable Substitution (Parameter Substitution)

PreviousHow to Concatenate String Variables in Bash [Join Strings]NextBash Parameter Expansion with Cheat Sheet

Last updated 1 year ago

When the original value of any expression is substituted by another value then it is called substitution. Bash variable substitution or parameter substitution is a very useful feature of bash. Generally, it is done in the bash by using the '$' character and the optional curly brackets ({}). The content of the bash variable can be checked or modified based on the programming requirements by using variable or parameter substitution.

In this tutorial, we will learn different ways of substituting bash variables.

Declaring variables in bash

A variable is a container that is used to store a particular value temporarily. No data type declaration is mandatory to declare bash variables. A variable name may contain characters, numbers, and underscores ( _ ). The ‘$’ symbol is not used to declare or assign a bash variable but the ‘$’ symbol is used to read the content of the assigned variable.

Any string or number can be assigned in a bash variable by using the assignment operator without any space. The ‘name’ variable assignment is valid because no space was not used before and after the ‘=’ symbol. The ‘quantity’ variable assignment is invalid because the space was used before and after the '=' symbol.

#Valid variable assignmentname="Exampledotcom"#Invalid variable assignmentQuantity = 100

The value of the ‘name’ variable (previously assigned) has been printed here by using the `echo` and `printf` commands.

#Print the variable using `echo`echo $name#Print the variable using `printf`printf "The name of the website is %s\n" $name

At first, the value of the $name variable which is 'Exampledotcom', has been printed without concatenating by any string value. Next, the $name variable has been printed by concatenating it with a string value.

What is variable substitution in bash?

The way of substituting the value of a variable by using another variable or command or parameter expansion is called bash variable substitution. We have discussed different types of bash variable substitutions in this section of this tutorial.

Substitute variable by another variable or parameter

Two different ways of substituting variables with string values have been shown here.

Substitute variable by '$' symbol

You can substitute the bash variable with another variable by reading the value of the variable by using the '$' symbol. The values of two variables have been substituted with another string value into a variable in the following script.

#Assign a string valuestring1="Bash" #Assign another string valuestring2=" Variable"#Substitute the variablessub="$string1$string2 Substitution"#Print the substituted valueecho "The substituted value is '$sub'"

The value of the $string1 variable is 'Bash' and the value of the $string2 variable that is ' variable' have been substituted with the string value, 'Substitution' into the $sub variable.

Substitute variable using the parameter

You can substitute bash variables by using “${parameter}”. In the following script, three variables have been initialized with three string values and substituted into another variable that has been printed later.

#Assign the first variablevariable1='Bash'#Assign the second variablevariable2=' Programming'#Assign the third variablevariable3=' Script'#Substitute the variablessub="${variable1}${variable2}${variable3}"#Print the substituted valueecho "The substituted value is '$sub'"

The value of $variable1 is 'Linux', the value of $variable2 is 'Op', and the value of $variable3 is 'Sys'. The values of these variables have been substituted into the variable, $sub.

Substitute variable by command

The command substitution is another way of substituting variables in bash. The ‘$()’ is used for applying command substitution. In this case, the variable is substituted by the output of a command. There are some differences between parameter substitution (‘${}’) and command substitution (‘$()’) which have been discussed in this section.

Difference between ‘${parameter}’ and ‘$(command)’:

Parameter Substitution
Command Substitution

It is defined by ‘${}’.

It is defined by ‘$()’.

It is used to store the value by associating it with a name, number, or special character.

It is used to store the output of any command.

It is useful when we require to add one or more characters or numbers immediately after the parameter value. For example: str="Book"echo "${str}s" Output: Books

It is useful when we require to add one or more characters with the output of any command. For example: str=$(pwd)echo "Current working directory: $str" Output: Current working directory /home/username

Use of command substitution:

The username of the currently logged-in user will be substituted in the $user variable by executing the command, `whoami` and the value of this variable will be printed later.

#Read the logged-in usernameuser=$(whoami)#Print the current usernameecho "The current username is $user"

According to the output, the currently logged-in username is 'ubuntu'.

Substitute variable by defining default shell variable

Many ways exist in bash to substitute the variable by defining the default shell variable. Three of them are ":=", ":-", and ":+". The ":=" is used to print the newly assigned value if the variable is not set before. The ":-" is used to print the previously assigned value if the variable is set before. The ":+" is used to print the newly assigned value if the variable is set before.

#Newly assigned value will be printed if the variable is unsetecho "${OS:=Ubuntu}"#Previously assigned value will be printed if the variable is setecho "${OS:-CentOS}"#Newly assigned value will be printed if the variable is setecho "${OS:+Debian}"

Here, the $OS variable was not initialized before. So, 'Ubuntu' has been printed in the first output. 'Ubuntu' has been printed in the second output because the $OS was set. 'Debian' has been printed in the third output because the $OS was set.

Array variable substitution

An array of numbers has been defined and the value of the third index of the array has been printed by array variable substitution in the following script.

#Declare an array of 6 numbersarr_variable=(45 90 34 12 90 51)#Print the 3rd element value of the arrayecho "The value of 3rd element is: ${arr_variable[2]}"

The 3rd index value of the array is 34 which has been printed here.

Substitute variable in single quotes

The way of substituting a variable with another variable with the string enclosed by a single quote ( ' ) has been shown in the following script.

#Assign a variablestring="Substitution"#Substitute the variable with single quotessub='Variable '$string' tutorial'#Print the substituted valueecho "The substituted value is '$sub'"

Here, the value of the $string variable has been substituted by adding it in the middle of two strings, ‘Variable ‘ and ‘ tutorial’.

Substitute variable using parameter expansion options

The variable can be substituted in different ways by using parameter expansion options. The use of parameter expansion to substitute the part of a variable has been shown in the following script.

#Assign a string value to a variablestring="Bash is a scripting language"#Find and replace the particular part of a variablesub="${string/scripting/popular}"#Print the substituted valueecho "The substituted value is '$sub'"

The value of $string is 'Bash is a scripting language' that has been substituted into the $sub after replacing the word, 'scripting' with 'popular' by using parameter expansion.

Conclusion

Bash variable substitution has been explained in multiple ways in this tutorial to clear the concept of variable substitution and it will help you to substitute variables in your script on demand.

using the parameter
default shell variable
using the '$' symbol
example of substitute variable in single quotes
example of array variable substitution
bash assign variable and print
Substitute variable by using parameter expansion options
Use of command substitution