Heschoon
Heschoon

Reputation: 3017

Insert variable value or default value if empty in a string

I want to insert the value of an environment variable in a string or a default value if the corresponding variable is not initialized.

Example:

if [ -z $MY_VAR ];
then
    MY_VAR="default"
fi

echo "my variable contains $MY_VAR"

I'm however using a lot of variables in my strings and the tests are cluttering my script.

Is there a way to make a ternary expression in my string?

Example of what I want to achieve (it doesn't work):

echo "my variable contains ${-z $MY_VAR ? $MY_VAR : 'default'}"

Upvotes: 18

Views: 21286

Answers (2)

Michael Kohl
Michael Kohl

Reputation: 66857

See Bash Default Values

→ echo "my variable contains ${MY_VAR:-default}"
my variable contains default

Upvotes: 25

chepner
chepner

Reputation: 532053

To actually set the value of the variable, rather than just expanding to a default if it has no value, you can use this idiom:

: ${MY_VAR:=default}

which is equivalent to your original if statement. The expansion has the side effect of actually changing the value of MY_VAR if it is unset or empty. The : is just the do-nothing command which provides a context where we can use the parameter expansion, which is treated as an argument that : ignores.

Upvotes: 30

Related Questions