Thursday 31 December 2015

Bash - basic script for checking positional params

My know-how of Bash scripting is pretty nil so I've been skimming through this guide the last few days to get to grips with the basic concepts. I've put together this basic script as a reminder to myself for future reference of how to pass in and parse positional params in a script:

#!/bin/bash

if [ $# -lt 2 ];
then echo "Must pass in at least two params."; exit 1;
fi

#set -x
GREETING="Hello"
echo "$GREETING $USER"
#set +x

echo ""
echo "\$0 = $0"
echo "\$1 = $1"
echo "\$2 = $2"
echo ""

[ -f $0 ] && (echo "File $0 exists.";) || (echo "File $0 doesn't exist.";)

echo ""

if [ $1 -eq $2 ]; then
echo "The value of \$1 is equal to the value of \$2.";
elif [ $1 -lt $2 ]; then
echo "The value of \$1 is less than the value of \$2.";
else echo "The value of \$1 is greater than the value of \$2.";
fi

echo ""

AREA=$[$1 * $2]
echo "\$AREA = \$1 * \$2 = $AREA"

case $AREA in
([-][0-9]*)
    echo "The value of \$AREA is negative.";;
([0-9])
    echo "The value of \$AREA is < 10.";;
([1-9][0-9])
    echo "The value of \$AREA is < 100.";;
*)
    echo "The value of \$AREA is >= 100.";;
esac

echo ""
echo "Goodbye $USER"

If I run this script as follows: bash MyScript.sh, then I'll see this output:

Must pass in at least two params.

If, however, I run this script as follows: bash MyScript.sh 5 4, then I'll see this output:

Hello adil

$0 = MyScript.sh
$1 = 5
$2 = 4

File MyScript.sh exists.

The value of $1 is greater than the value of $2.

$AREA = $1 * $2 = 20
The value of $AREA is < 100.

Goodbye adil

That's it. That's a basic script which demonstrates how to perform some conditional checks on positional params passed into a script.

No comments: