Shell script to pass multiple arguments with options

This tutorial will help you to pass multiple arguments in a more organized manner. I have used two arguments “t” and “d” here.  The first argument “t” will accept task value and based on the task value you can perform the respective action for a particular date(“d”).

In a real world example, if you want to write a bash script which will accept database DML operation as an argument  and based on the DML command type, perform some operation for a specific date.

example:

$ sh script.sh -t insert -d 2019-06-18

$ sh script.sh -t update -d 2019-06-18

$ sh script.sh -t select -d 2019-06-18

script.sh

#!/bin/bash

if (($# == 0)); then
    echo "Please pass arguments -t <task1><task2>... -d <date>.."
    exit 2
fi

while getopts ":t:d:" opt; do
    case $opt in
        t)
            echo "-t was triggered, Parameter: $OPTARG" >&2
            TASKS=$OPTARG
            ;;
        d)
            echo "-d was triggered, Parameter: $OPTARG" >&2
            RDATE=$OPTARG
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
        :)
            echo "Option -$OPTARG requires an argument." >&2
            exit 1
            ;;
    esac
done
echo "Go thru selection"
for TASK in $TASKS;
do
    if [ "$TASKS" == "d1" ]
    then
        echo "Inside the d1"
        echo -n "Choose option p-partial, hit enter for all >"
        read DType
        echo "You have choosen $DType"

    fi
    echo "Task: $TASK"
done

##Check Date
date "+%Y-%m-%d" -d "$RDATE" > /dev/null  2>&1
if [ $? != 0 ]
then
	echo Start date $start is NOT a valid YYYY-MM-DD date
	exit 1
fi

 

Uses:

$ sh script.sh -t d1 -d 2019-06-18

Few More Shell Script Reference

https://github.com/roopendra/devops/tree/master/bash_scripting

(Visited 1,495 times, 21 visits today)