Setting a Shell Variable Default Value

Author: MikeW    Date: 2016-09-22 16:05   

A typical situation in computing is to check and see if a value exists and if it does not, providing a default value. Turns out you can do this with a Bash script easily.

 1#!/bin/bash
 2
 3export PORT="8081"
 4export HOST="myhost"
 5
 6echo $PORT
 7echo $HOST
 8
 9# Option 1: Check and re-assign
10
11export MYPORT="${PORT:-8080}"
12export MYHOST="${HOST:-localhost}"
13
14echo $MYPORT
15echo $MYHOST
16
17export JAVA_OPTS="-Dhttp.port=$MYPORT -Dhttp.host=$MYHOST"
18
19echo JAVA_OPTS is
20echo $JAVA_OPTS

Use the “:-“ operator to assign a value if none exists. If the environment variable is set, then that value is returned.

This script builds an environment variable based on other environment variables. Values will get set even if the originals are commented out.