Setting Default Values For Variables In Bash

10 Mar 2013

How to set default values to variables in bash? The idea is that the variables are assigned to some values when you explicitly assign them, but still get some default values when you DON’T explicitly do that.

Here is how:

# set VARIABLE to the value of first arg to the script
# if first arg is not given, set it to DEFAULTVALUE
VARIABLE=${1:-DEFAULTVALUE}

# some more examples
tmpdir=/tmp
defvalue=1

# Default to /tmp dir
DIR=${1:-$tmpdir}       

# Default to 1
VALUE=${2:-$defvalue}   

echo $DIR
echo $VALUE

# after you run the code above, you get the following results;
# assume the above script is saved in dfvalue.sh
$ ./dfvalue.sh /dev 23
/dev
23

$ ./dfvalue.sh
/tmp
1

REFERENCE