I've seen several different methods of using default values in parameter expansions in Bourne-derived shells: :=
, =
, :-
and -
. I'm wondering how they differ. The manual says that -
and =
handle null values differently from :-
and :=
. But as far as I can tell, :=
== :-
and =
== -
. Is this true?

- 46,058
- 19
- 106
- 116

- 3,758
- 3
- 32
- 54
-
Here it is: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion – Barmar Jul 01 '20 at 18:03
-
The manual describes the behavior of each, but as far as I can tell, :- and := behave exactly the same. I'd like to confirm whether that is really the case. – Jacob Stern Jul 01 '20 at 18:06
-
They do not; the equal forms actually change the value of the parameter is the default is used. – chepner Jul 01 '20 at 18:08
-
1The difference is that `:=` assigns the default value to the variable in addition to returning it. – Barmar Jul 01 '20 at 18:08
-
1Add `echo $my_var` and you'll see the difference. – Barmar Jul 01 '20 at 18:09
-
This is also covered in https://wiki.bash-hackers.org/syntax/pe – Charles Duffy Jul 01 '20 at 18:10
3 Answers
A demonstration of :=
vs :-
:
$ unset foo
$ echo ${foo:-bar}
bar
$ echo foo
$ echo ${foo:=bye}
bye
$ echo $foo
bye
:-
only affects the result of the expansion, leaving the parameter unchanged. :=
actually assigns the default value to the parameter if it is null or unset.
=
works analogously to -
regarding unset parameters; it only changes the value of foo
if it is unset, not if it has a null value.

- 497,756
- 71
- 530
- 681
The documentation is explicit.
With the =
forms, emphasis added:
If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. [...]
With the other forms:
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
No assignment, modifying the parameter's value when later expanded as a variable, takes place without using an =
form.

- 280,126
- 43
- 390
- 441
Even though the question has already been answered, I just want to post a link to the shell bible, where you can find a great explanation not only to the parameter expansion, but to almost everything shell related.

- 1,333
- 22
- 36