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.
Contact Us