Friday, September 27, 2013

What is the difference when assigning a bash variable value with this syntax?

Sorry if this is something really simple or has already been asked, yet 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 usual way of assigning a value like this:

MY_BASH_VAR=myvalue$ echo "$MY_BASH_VAR"myvalue

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=42bruce@lorien:~$ A=${A:-5}bruce@lorien:~$ echo $A42

No comments:

Post a Comment