Pass date as mandatory arguments in bash script

I came across a use case where I have to write a shell script to perform some action on two date ranges. The first argument would start date and the second argument as end date.

To validate missing argument we can also check $1 and $2 null value and display the error message. However, I was looking for a solution where I can check null argument, missing argument including date validation. Here is the shell script snippet to pass date range as mandatory arguments and validate the date value.

How to check mandatory arguments in bash script

tutorial.sh

#!/usr/bin/bash
start=$1
end=$2

read -r -d '' USES << EOM
Incorrect arguments passed
    Uses:
    tutorial.sh  
    tutorial.sh 2019-01-01 2019-01-05
EOM

case $# in
      1)
        date "+%Y-%m-%d" -d "$start" > /dev/null  2>&1
        if [ $? != 0 ]
        then
            echo Start date $start is NOT a valid YYYY-MM-DD date
            exit 1
        else 
           if [ -z "$end" ]
              then
                echo "$USES"
                exit 1
            fi
        fi
    ;;
    2)
        date "+%Y-%m-%d" -d "$end" > /dev/null 2>&1
        if [ $? != 0 ]
        then
            echo End date $end is NOT a valid YYYY-MM-DD date
            exit 1
        fi
    ;;
    *)
        echo "$USES"
    exit 1;;
esac

start=$(date -d $start +%Y%m%d)
end=$(date -d $end +%Y%m%d)

while [[ $start -le $end ]]
do
    echo $start
    start=$(date -d"$start + 1 day" +"%Y%m%d")
done

Uses

 $ tutorial.sh 2019-01-01 2019-01-05 
20190101
20190102
20190103
20190104
20190105
Pass date as mandatory arguments in bash script
(Visited 1,744 times, 69 visits today)