Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

operators

bash

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?

like image 630
Adam Matan Avatar asked Apr 24 '26 00:04

Adam Matan


2 Answers

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.

like image 75
fedorqui 'SO stop harming' Avatar answered Apr 26 '26 16:04

fedorqui 'SO stop harming'


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.

like image 36
Adam Matan Avatar answered Apr 26 '26 16:04

Adam Matan