Variable Substitution

The shell allows us to manipulate the value of a variable based upon its initialization status. 

Sr No. Expression Significance
1 ${myVariable} substitute the value of myVariable.
2 ${myVariable:-value} If myVariable is not-set (or null) then the value is substituted for myVariable.
3 ${myVariable:=value} If myVariable is not-set (or null), then it is set to value.
4 ${myVariable:? message} If myVariable is not-set (or null) then the message is printed as standard error.
5 ${myVariable:+value} If myVariable is set then the value is substituted for myVariable.

Example:

These expressions are demonstrated in the below shell script.

#!/bin/sh


# If myVariable is unset or null 
# then assign 12 to it
echo ${myVariable:- 11}
echo "1. The value of myVariable is ${myVariable}"


# If myVariable is unset or null 
# then assign "w3wiki" to it
echo ${myVariable:="w3wiki"}
echo "2. Value of myVariable is ${myVariable}"

# unset myVariable
unset myVariable

# If myVariable is set then substitute 
# the value
echo ${myVariable:+"w3wiki"}
echo "3. Value of myVariable is $myVariable"

myVariable="w3wiki"

# If myVariable is set then substitute 
# the value
echo ${myVariable:+"Bhuwanesh"}
echo "4. Value of myVariable is $myVariable"

# If myVaraible is not-set or null then 
# print the message
echo ${myVariable:?"message"}
echo "5. Value of myVariable is ${myVariable}"

unset myVariable

# If myVaraible is not-set or null then
# print the message
echo ${myVariable:?"message"}
echo "6. Value of myVariable is ${myVariable}"

Output:

Shell Scripting – Substitution

There are certain expressions that convey special meanings. In other words, they are not what they look like. A shell carries out substitution whenever it encounters such expressions. Hence, substitution is defined as a mechanism carried out by a shell in which it substitutes the value of an expression with its actual value.

Similar Reads

Escape sequences:

An escape sequence is a group of character(s) that does not represent its actual value when it is used as a string literal. Some of the escape sequences are listed below:...

Variable Substitution:

The shell allows us to manipulate the value of a variable based upon its initialization status....

Command Substitution:

Command substitution is a mechanism that is followed by programmers in a bash script. In this mechanism, the output of a command replaces the command itself. Bash operates the expansion by executing a command and then replacing the command substitution with the standard output of the command. In simple words, the output of a UNIX command is bundled and then used as a command....

Contact Us