3

I am looking at parameter expansion using ${parameter:-word} versus ${parameter:=word}.

Here is some relevant documentation:

${parameter:-word} If parameter is unset or null, the expansion of word is substituted.

${parameter:=word} If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted.

Certainly, the key difference is in the first sentence of each description, substituted versus assigned.

But in actuality, I do not know what happens when something is substituted versus when something is assigned.

Finally, when is it appropriate to use one versus the other?

legends2k
  • 243
Pietru
  • 389
  • 1
  • 17

1 Answers1

7

Consider this example:

#!/bin/bash

echo "${parameter:-a}" echo "${parameter:-b}" echo "${parameter:=c}" echo "${parameter:=d}"

And an example run of the script:

$ bash ex.sh
a
b
c
c

In the first echo, parameter is unset, so a is substituted. This prints a.

In the second echo, parameter is still unset, so b is substituted. This prints b.

In the third echo, parameter is still unset, so parameter is assigned the value c, then parameter is evaluated. This prints c.

In the fourth echo, parameter is set (it was set to c in the previous statement), so its value is printed. This prints c again.

From this, you can see that ${parameter:-word} evaluates to word if parameter is unset or null, but does not affect the value of parameter, while ${parameter:=word} will set the value of parameter if it was unset of null.

Andy Dalton
  • 13,993
  • Thank you for the example. One thing I cannot figure out are the circumstances that would push you to use ${parameter:-a}. I currently use ${parameter:=d} to set default parameters for function arguments. – Pietru Jul 08 '21 at 02:20
  • @Pietru you can use ${parameter:-word} if you want the script to be able to determine that parameter was unset/null after you initially try to use its value. – Andy Dalton Jul 08 '21 at 02:23
  • Does your comment also mean that I can do varp=${parameter:-word} ? Meaning set varp to word without setting parameter. However, I do not see a difference using parameter=${parameter:-word} and parameter=${parameter:=word}. – Pietru Jul 08 '21 at 02:30
  • @Pietru Does your comment also mean...? Yes. However, I do not see a difference... There really isn't a difference in that case. – Andy Dalton Jul 08 '21 at 02:32
  • Some people denigrate the use of parameter=${parameter:=word}, as it is a form of parameter expansion that intrinsically performs variable assignment, only to redundantly assign the result of the expansion to the same variable once again. How is ${parameter:=word} customarily used ? – Pietru Jul 08 '21 at 02:42
  • The solution would then be to use : ${parameter:=word} – Pietru Jul 08 '21 at 07:30