6

Defaulting Argument Values in a BASH script | The Anti-Kyte

 3 years ago
source link: https://mikesmithers.wordpress.com/2021/09/13/defaulting-argument-values-in-a-bash-script/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Defaulting Argument Values in a BASH script

Posted on September 13, 2021

I recently found out (again) how to default argument values in a shell script, so I thought I’d write it down this time.
The ABBA flavour in what follows is because we’re talking about BASH – the Bourne Again SHell and Bjorn Again are an ABBA tribute band. This is quite handy because the ABBA back catalogue is rather versatile having already lent itself to an explanation Oracle password complexity.

Welcome to the inside of my head. Sorry about the mess…

Let’s start with a simple script – abba.sh :

#!/bin/bash
if [ $# = 0 ];  then
echo 'No argument values passed in'
else
TRACK=$1
echo $TRACK
fi;

…which we now make executable :

chmod u+x abba.sh

Run this – first with no arguments passed in and then with a single argument and we get :

If we want to default the value of $TRACK (and let’s face it, who doesn’t love a bit of Dancing Queen), we can do the following (saved as abba2.sh) …

#!/bin/bash
TRACK="${1:-Dancing Queen}"
if [ $# != 1 ];  then
echo 'No argument values passed in'
fi;
echo $TRACK

Now, when we run this, we can see that it’ll accept an argument as before. However, if no argument is passed in the argument count is unaffected but the variable is initialized to it’s default value :

Advertisements
Report this ad

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK