35

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

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

11

Not directly.

my_str="${var_name:-${another_var:-default}}"
1
  • Could you provide a link to official documentation?
    – draev
    Sep 15 '20 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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