You want your script to provide a useful default date, and perhaps prompt the user to verify it.
Using the GNU date command, assign the most likely date to a variable, then allow the user to change it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#!/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" |
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).
We use code like this in scripts that generate SQL queries. The script runs at a given time and creates a SQL query for a specific date range to generate a report.