Supplying a Default Date

Problem

You want your script to provide a useful default date, and perhaps prompt the user to verify it.

Solution

Using the GNU date command, assign the most likely date to a variable, then allow the user to change it:

#!/usr/bin/env bash
# cookbook filename: default_date

# Use Noon time to prevent a script running around midnight and a clock a
# few seconds off from causing off by one day errors.
START_DATE=$(date -d 'last week Monday 12:00:00' '+%Y-%m-%d')

while [ 1 ]; do
    printf "%b" "The starting date is $START_DATE, is that correct? (Y/new date)"
    read answer

    # Anything other than ENTER, "Y" or "y" is validated as a new date
    # could use "[Yy]*" to allow the user to spell out "yes"...
    # validate the new date format as: CCYY-MM-DD
    case "$answer" in
        [Yy]) break
            ;;
        [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9])
            printf "%b" "Overriding $START_DATE with $answer\n"
            START_DATE="$answer"
            ;;

        *)   printf "%b" "Invalid date, please try again...\n"
            ;;
    esac
done

END_DATE=$(date -d "$START_DATE +7 days" '+%Y-%m-%d')

echo "START_DATE: $START_DATE"
echo "END_DATE:   $END_DATE"

Discussion

Not all date commands support the -d option, but the GNU version does. Our advice is to obtain and use the GNU date command if at all possible.

Leave out the user verification code if your script is running unattended or at a known time (e.g., from cron).

See Formatting Dates for Display for information about how to format the dates and times.

We use code like this in scripts that generate SQL queries. ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.