Parameter unwinding (parameter expansion) is the procedure that the shell uses to provide variable values in a program.
Expansion operators include substitution operators and pattern matching operators
Substitution operators
Operator |
Replacement instructions |
Memory |
${varname:-word} |
If varname exists and is not NULL, its value is returned, otherwise word is returned. |
Empty returns Word |
${varname:=word} |
Returns the value of VarName if it exists and is not NULL, otherwise, sets the value of varname to Word and returns its value. Change the value of the variable. |
Empty returns Word and changes the value of the variable |
${varname:?message} |
If varname exists and is not NULL, its value is returned; otherwise, Varname:message is displayed and the current command or script exits. Omitting the message will show the default information parameter null or not set. |
Empty displays a warning and exits. |
${varname:+word} |
Returns word if varname exists and is not NULL, otherwise NULL is returned. |
non-empty returns word, empty returns NULL. |
Example:
$ echo ${varname} $ echo ${varname:var1}
$ echo ${varname:-var1} Var1
$ echo ${varname:+var1}
$ echo ${varname:=var2} Var2
$ echo ${varname:+var1} Var1
$ echo ${varname} Var2 $ echo ${varname:?warning1} Var2 $ varname= $ echo ${varname} $ echo ${VARNAME:+VAR5} $ echo ${varname}
$ echo ${varname:?warning2} -bash:varname:warning2
|
Pattern matching Operators
Operator |
Replace |
Memory |
${variable#Pattern} |
If the pattern matches the beginning of the variable value, the shortest part of the match is deleted and the remainder is returned. |
Delete the Shortest (one #) part of the beginning |
${variable# #Pattern} |
If the pattern matches the switch of the variable value, the longest portion of the match is deleted and the remainder is returned. |
Delete switch maximum (two #) section |
${variable%pattern} |
If the pattern matches the end of the variable value, the shortest part of the match is deleted and the rest is returned. |
Delete end shortest ( one%) section |
${variablepercent pattern} |
If the pattern matches the end of the variable value, the longest portion of the match is deleted and the remainder is returned. |
Delete End -of-length (two%) section |
Example:
$ Export Myvar=/home/merlin/myfile.log.tail $ echo ${myvar} /home/merlin/myfile.log.tail $ echo ${myvar#/*/} Merlin/myfile.log.tail $ echo ${myvar##/*/} Myfile.log.tail $ echo ${myvar%.*} /home/merlin/myfile.log $ echo ${myvar%%.*} /home/merlin/myfile |
Shell parameter expansion