Adam Matan
Adam Matan

Reputation: 136341

bash: "${A:-B}" operator

I've been refactoring some bash code, and stumbled upon this bash notation:

"${string_a:-string_b}"

I've played a little with this on the command line:

$ echo "${string_a:-string_b}"
string_b
$ export string_a=string_a_value
$ echo "${string_a:-string_b}"
string_a_value

I seems that the {a:-b} notation returns the value of variable a if it is defined, or the string b otherwise.

Where can I find a more formal definition for this operator?

Upvotes: 1

Views: 4632

Answers (3)

Adam Matan
Adam Matan

Reputation: 136341

Another useful link is the Shell Parameter Expansion section in the Bash Reference Manual. The :- operator is defined as:

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

By the way, bash features three similar operators ${parameter:=word}, ${parameter:?word} and ${parameter:+word}, defined in that section.

Upvotes: 3

rzymek
rzymek

Reputation: 9281

You can access bash documentation using man bash. To search type /

${parameter:-word}

Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

Upvotes: 2

fedorqui
fedorqui

Reputation: 290015

Peer pressure, I post my comment as an answer : )

I like this reference card: Advanced Bash-Scripting Guide , specifically in your case it will be useful "# Table B-4. Parameter Substitution and Expansion".

I do not copy any issue they indicate not to violate any copyright. Just find all information there.

Upvotes: 4

Related Questions