Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm really fond of "null coalescing", where you can set a variable to the first "non-null" value in a list of things. Many languages support this, for example:

C#:

String myStr = string1 ?? string2 ?? "default";

JavaScript:

var myStr = string1 || string2 || "default";

...etc. I'm just curious if this can be done in Bash to set a variable?

pseudo:

MY_STR=$ENV{VAR_NAME}??$ANOTHER_VAR??"default";
share|improve this question

2 Answers 2

up vote 9 down vote accepted

The POSIX shell (so includes bash) equivalent would be:

${FOO:-${BAR:-default}}

See also the:

${FOO-${BAR-default}}

variant which checks whether the variable is set or not instead of whether it resolves to the empty string or not (which makes a difference in the cases where a variable is set but empty).

share|improve this answer

Not directly.

my_str="${var_name:-${another_var:-default}}"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.