Parameter and Variable Expansion

(this post if part of the material I cover in my devops course)

About Parameter Expansion

This post is based on th shell parameter expansion documentation.

  • The ‘$’ character introduces several expansions:
    • parameter expansion
    • command substitution
    • arithmetic expansion
  • Parameter expansion mainly replaces a parameter reference with its value.
  • When we're talking about shell parameters we refer to variables, positional parameters and special parameters
  • The parameter name or symbol to be expanded may be enclosed in braces.
    • braces are optional
    • braces serve to protect the variable to be expanded from characters immediately following it.
      Example:
1$> mymsg=hello
2$> printf "Message: %s\n" $mymsg
3Message: hello
4$> printf "Message: %s\n" $mymsgworld
5Message: 
6$> printf "Message: %s\n" ${mymsg}world
7Message: helloworld
8$> 
  • If you reference a positional parameter with more than a single digit:
1printf "%s\n" ${10}

Using ! to set level of indirection

It is best understood by an example:

1$ var1=var2
2$ var2=5
3$ echo $var1
4var2
5$ echo $!var1
6var1
7$ echo ${!var1}
85
9$
  • This is sometimes called This is known as indirect expansion

More Advanced form of parameter expansion

  • ${parameter:-word}
    If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted:
1$ unset username
2$ echo ${username:-Dave}
3Dave
4$ 
5$ username=Jane
6$ echo ${username:-Dave}
7Jane
8$ 
  • ${parameter:=word}
    Same as before, but also the value of parameter is then substituted.
1$ 
2$ unset username
3$ echo ${username:=Dave}
4Dave
5$ echo $username
6Dave
7$ 
  • ${parameter:?word}
    If parameter is null or unset, the expansion of word is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
1$ 
2$ defaultName=Dave
3$ echo ${username:?$defaultName}
4bash: username: Dave
5$ echo $?
61
7$ 
  • ${parameter:+word}
    Not really expanding parameter, just check if it exists, then substitute word.
    (look for the opposite with a minus sign)
1$ 
2$ msg="is set"
3$ unset username
4$ echo ${username:+username $msg}
5
6$ username=Dave
7$ echo ${username:+username $msg}
8username is set
9$ 
  • ${parameter:offset}
    ${parameter:offset:length}
    This is referred to as Substring Expansion:
1$ abc=abcdefghijklmnopqrstuvwxyz
2$ echo ${abc:5}
3fghijklmnopqrstuvwxyz
4$ echo ${abc:5:8}
5fghijklm
6$ echo ${abc: -7}
7tuvwxyz
8$ echo ${abc: -7:4}
9tuvw

Read more options for parameter expansion in the documentation.