0

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?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why are you answering a duplicate.
I usually attach not too much attention on a question being duplicate or not. Probably I should have done it in this case. Now it's too late :) ...
3

You can have two files:

  • a file containing the default value of variables.
  • the client file

Source the default file and then the one from the client. This way, customer's values will be overwritten.

Test

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.

2 Comments

Wow! Much cleaner and easier to maintain than the parameter expansion way, thanks.
@LotusH nice that it was useful for you : )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.