I have a bunch of environment variables passed from client code, if they are not set, I need to set default values to them.
Except testing them one by one with a lot of if ...; then ... fi
, is there a clean way to do this?
I have a bunch of environment variables passed from client code, if they are not set, I need to set default values to them.
Except testing them one by one with a lot of if ...; then ... fi
, is there a clean way to do this?
You can use parameter expansion like this:
foo=${foo:-default value}
This will set $foo
to "default value"
if it is not defined or empty(!).
Note that using the above code, you can't distinguish between a variable which has not being defined and a variable which has been explicitly set to an empty string. If that's fine for you, use it.
You can have two files:
Source the default file and then the one from the client. This way, customer's values will be overwritten.
Let's have these two files:
$ cat default
export var1="foo"
export var2="bar"
export var3="bee"
$ cat customer
export var2="yeah!"
Now, let's source them:
$ source default
$ env | grep "^var"
var1=foo
var3=bee
var2=bar
Then let's get customer
's file:
$ source customer
$ env | grep "^var"
var1=foo
var3=bee
var2=yeah!
As you see, variable $var2
has not the value from customer
's file, whereas the others have the value sest in default
.