-2

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?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Jacob Stern
  • 3,758
  • 3
  • 32
  • 54

3 Answers3

3

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

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.

dsax7
  • 1,333
  • 22
  • 36