0

Sorry if this is something really simple or has already been asked, but due to the nature of the question I cannot think of any search terms to put on search engines.

Lately I have seen some bash scripts that they assign variable values like this:

$ MY_BASH_VAR=${MY_BASH_VAR:-myvalue}
$ echo "$MY_BASH_VAR"
myvalue

What is the difference from the most common way of assigning a value like this:

MY_BASH_VAR=myvalue
$ echo "$MY_BASH_VAR"
myvalue
Vangelis Tasoulas
  • 3,109
  • 3
  • 23
  • 36

2 Answers2

2

You can look at http://linux.die.net/man/1/bash

${parameter:-word}  Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

This provides a default value : MY_BASH_VAR keeps its value if defined otherwise, it takes the default "myvalue"

bruce@lorien:~$ A=42
bruce@lorien:~$ A=${A:-5}
bruce@lorien:~$ echo $A
42
Bruce
  • 7,094
  • 1
  • 25
  • 42
  • Note that with `:-`, `A` will also receive the default value if it is currently set to the empty string. – chepner Jul 09 '13 at 13:07
2

Suppose the $MY_BASH_VAR was already set. In this case, it will keep the same value. If not, it will get myvalue.

case 1) $MY_BASH_VAR already set.

$ MY_BASH_VAR="hello"
$ MY_BASH_VAR=${MY_BASH_VAR:-myvalue}
$ echo "$MY_BASH_VAR"
hello

case 2) $MY_BASH_VAR not previously set.

$ MY_BASH_VAR=${MY_BASH_VAR:-myvalue}
$ echo "$MY_BASH_VAR"
myvalue

case 3) $MY_BASH_VAR set to the empty string.

$ MY_BASH_VAR=""
$ MY_BASH_VAR=${MY_BASH_VAR:-myvalue}
$ echo "$MY_BASH_VAR"
myvalue
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Note that with `:-`, `MY_BASH_VAR` will also receive the default value if it is currently set to the empty string. – chepner Jul 09 '13 at 13:06
  • Oh, that's true, didn't remember to mention it in my answer. Just updated it. Thanks! – fedorqui Jul 09 '13 at 13:13