Seems both make absolutely same actions.
Empty $var
returns defaultvalue
in both cases:
$ var=
$ echo ${var:-defaultvalue}
defaultvalue
$ var=
$ echo ${var:=defaultvalue}
defaultvalue
Not empty $var
return it's value in both cases:
$ var=var
$ echo ${var:-defaultvalue}
var
$ var=var
$ echo ${var:=defaultvalue}
var
$var
not set at all - returns defaultvalue
in both cases:
$ unset var
$ echo ${var:-defaultvalue}
defaultvalue
$ unset var
$ echo ${var:=defaultvalue}
defaultvalue
In simple words, they do not have any initial value. Method 1: We can set variables with default or initial values in shell scripting during echo command with the help of the assignment operator just after the variable name.
You can use something called Bash parameter expansion to accomplish this. To get the assigned value, or default if it's missing: FOO="${VARIABLE:-default}" # If variable not set or null, use default. # If VARIABLE was unset or null, it still is after this (no assignment done).
They are similar only that ${var:=defaultvalue}
assigns value to var as well and not just expand as like it.
Example:
> A='' > echo "${A:=2}" 2 > echo "$A" 2 > A='' > echo "${A:-2}" 2 > echo "$A" (empty)
Positional or special parameters cannot be assigned using :=
way. See this example:
args() { v=${1:=one}; echo "$v"; }
args
-bash: $1: cannot assign in this way
And this:
args() { v=${1:-one}; echo "$v"; }
args
one
As per man bash
: (emphasis is mine to highlight the difference)
${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
${parameter:=word}
Assign Default Values. 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.
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