I'm looking at several bash scripts that use :=
in between ${ }
. For example, the pattern looks like this:
export VAR=${VAR:=value}
What is this doing? Is it assigning value to VAR if VAR does not exist?
Here are all the ways in which variables are substituted in Shell: ${variable} This command substitutes the value of the variable. ${variable:-word} If a variable is null or if it is not set, word is substituted for variable.
In the bash shell, ${! var} is a variable indirection. It expands to the value of the variable whose name is kept in $var . The variable expansion ${var+value} is a POSIX expansion that expands to value if the variable var is set (no matter if its value is empty or not).
- 1 means the first parameter passed to the function ( $1 or ${1} ) - # means the index of $1 , which, since $1 is an associative array, makes # the keys of $1.
${0} is the first argument of the script, i.e. the script name or path.
As per documentation:
${parameter:=word}
If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
So it exports the VAR value with its value, or if it is unset/null it is exported with literal value
.
From the man page:
${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of param‐ eter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
In other words, it basically lets you specify a default value for a variable. If the variable is unset/null, then it will be set to that value and the value will be used as the expansion as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With