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'}"
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.
See Bash Default Values
→ echo "my variable contains ${MY_VAR:-default}"
my variable contains default
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With