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?

dotslashlu
  • 3,361
  • 4
  • 29
  • 56

2 Answers2

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.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Why are you answering a duplicate. – 123 Apr 20 '16 at 09:12
  • 3
    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 :) ... – hek2mgl Apr 20 '16 at 09:16
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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598