Bash – Setting a shell variable in a null coalescing fashion

bashshellvariable

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";

Best Answer

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).

Related Question