Parameter substitution in linux shell scripting

In this topic, you will learn how to substitute the parameters.
 
firstName=paul
lastName=watson

fullName=${firstName} ${HOSTNAME}
echo “$fullName”

Default parameters

In case, the variable is not initialized (null), you may want to use default value. You can use below syntax to specify the default value for the parameter.
 
${parameter-defaultValue} 
# This means that if the parameter is not declared, use defaultValue

${parameter:-defaultValue} 
# This means that if the parameter is declared and it’s value is null, use defaultValue


Below command will print 2 as we have not declared num
 
echo ${num-2}
num=
Below command will print 2 as we have declared num but the value is null
 
echo ${num:-2}
Below command will print 111 as we have declared num and it’s value is not null.
 
num=111
echo ${num:-2}

Print error message if variable is not declared or is null If the variable is not declared, Error_Message is printed.
 
${variable?Error_Message}
In below syntax, if the variable is declared and it is null, Error_Message is printed.
 
${parameter:?Error_Message}
Printing the length of variable value Below statement will print length of variable. If it is array, it returns the length of the first element in the array.
 
${#variable}
Deleting the shortest and longest matching pattern from the beginning of the variable # means it will delete the shortest matching pattern.
 
${variable#pattern}
## means it will delete the longest matching pattern.
 
${variable##pattern}
Deleting the shortest and longest matching pattern from the end of the variable % means it will delete the shortest matching pattern.
 
${variable%pattern}
%% means it will delete the longest matching pattern.
 
${variable%%pattern}
Replacing the pattern / means replace the first occurrence of the pattern.
 
${variable/Pattern/Replacement}
// means replace all the occurrences of the pattern.
 
${variable//Pattern/Replacement}
Below command can be used to replace the pattern only if prefix matches the pattern.
 
${variable/#Pattern/Replacement}

Below command can be used to replace the pattern only if prefix matches the pattern.
 
${variable/%Pattern/Replacement}

Web development and Automation testing

solutions delivered!!