1

VAR=${VAR:-value}

The purpose is to set the environment variable VAR to value unless it's already set.

I see it works in bash and dash, but how portable is it?

1 Answer 1

4

This assignment is portable, it works in any POSIX shell. POSIX define this expansion as:

${parameter:-word}

Use Default Values. If parameter is unset or null, the expansion of word shall be substituted; otherwise, the value of parameter shall be substituted.

But this also sets VAR to value if VAR was set and null. To set VAR to value unless it's already set, you must use:

VAR=${VAR-value}

Omitting the colon make substitution occur only if the variable is unset:

In the parameter expansions shown previously, use of the colon in the format shall result in a test for a parameter that is unset or null; omission of the colon shall result in a test for a parameter that is only unset.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .