Default values for environment variables


In ruby, the ||= operator will assign a given value to a variable, if that variable does not already have a value. For example:

puts foo  # => nil
foo ||= "bar"
puts foo  # => "bar"
foo ||= "baz"
puts foo  # => "bar"

This will assign "bar" to foo, unless foo is already set. In other words, it will make "bar" the default value of foo.

I recently had to do this is bash, and it turns out bash has similar functionality. This is the bash equivalent:

echo $FOO  # => ""
export FOO=${FOO:-"bar"}
echo $FOO  # => "bar"
export FOO=${FOO:-"baz"}
echo $FOO  # => "bar"