Search code examples
bashshellparameter-expansion

parameter expansion default ":=" vs "=" vs ":-" vs "-"


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?


Solution

  • 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.