Trinix Quick Tip!
Assigning a Default Value to a Variable in BASH

I was recently writing a script that would take an a optional command line argument that would set a delay and a prefix string. I needed the functionality that if the user didn’t set these optional command line arguments when calling the script, that a default  values would be used to fall back on.

The logic for every programming language pretty much the same & it’s usually just a matter of figuring out the correct syntax to achieve your desired results. I know how to do this in PHP & Javascript but wasn’t sure of the syntax to achieve this using BASH.

Well, it was in fact a matter of syntax and I managed to figure out how to get the result I was looking for. I wanted to share my findings since the syntax is a bit unconventional.

So in the 1st part of my script I have a conditional loop that iterates over the command line arguments and the ones that are given by the user are set and if an option argument wasn’t given, that variable does not get set.

while getopts ":p:d:" arg; do
    case $arg in
        p) prefix=$OPTARG;;
        d) delayValue=$OPTARG;;

In the section of code that follows the loop through the command line arguments I have each variable that can be set through the command line listed with the special default syntax so in the event that it isn’t set through the command line, I at least have a built in default value to fall back on.

BASH Default Variable Example:

The syntax is:

: "${prefix:='default_prefix'}";
: "${delayValue:=5}";

This assigns ‘default_prefix’ to the $prefix variable and 5 to the variable $delayValue if it is not defined already.

One thing to also note is the use of double quotes. Now, my total experience with BASH is probably about 40 hours, so I’m no expert, but from what I’ve read, the double quote will prevent word splitting and globbing of the variable.



I got this tip from a StackOverflow post (listed below) and the most helpful post I found was about a third of the way down the page.

Leave a Reply

Your email address will not be published. Required fields are marked *