Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert variable value or default value if empty in a string

Tags:

bash

scripting

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'}"
like image 863
Heschoon Avatar asked May 08 '15 09:05

Heschoon


2 Answers

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.

like image 145
chepner Avatar answered Oct 11 '22 20:10

chepner


See Bash Default Values

→ echo "my variable contains ${MY_VAR:-default}"
my variable contains default
like image 38
Michael Kohl Avatar answered Oct 11 '22 20:10

Michael Kohl