DanH
DanH

Reputation: 5818

What does ":-" do in a variable declaration?

I have been tasked with assuming control over some bash scripts, and looking through them I've come across the following notation:

INITPATH=${INITPATH:-"include"}

As far as I can tell this does something similar to a = a || b and allows the setting of a default value if the environment variable is not set?

I guess I'm just looking for some clarification on this, and whether the ":-" can be broken down or used in other contexts. I've as yet failed to come across it flicking through various Bash documentation.

Upvotes: 0

Views: 83

Answers (2)

Guru
Guru

Reputation: 1883

This has most of how you can substitute

echo "$\{var}"
echo "Substitute the value of var."


echo "1 - $\{var:-word}"
echo "If var is null or unset, word is substituted for var. The value of var does not change."


echo "2- $\{var:=word}"
echo "If var is null or unset, var is set to the value of word."


echo "5-$\{var:?message}"
echo "If var is null or unset, message is printed to standard error. This checks that variables are set correctly."


echo "3 - $\{var:+word}"
echo "If var is set, word is substituted for var. The value of var does not change."

Upvotes: 0

devnull
devnull

Reputation: 123458

From the manual:

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

In your example, if INITPATH is unset/null, it's set to include.

Upvotes: 3

Related Questions