I'd like to be able to pass dates to a script in the form of yyyy-mm, mm/yyyy, yyyy-mm-dd, and mm/dd/yy.
For example:
$ ./parse.sh 2021-03 2021-03-14 3/14/19 11/2019
year: 2021 / month: 03 / day:
year: 2021 / month: 03 / day: 14
year: 2019 / month: 03 / day: 14
year: 2019 / month: 11 / day:
This script works for values that have year, month, and day, but not just for year and month:
#!/usr/bin/env bash
for arg in "$@"
do
# echo "parsing $arg..."
read -r y m d <<< "$(date ' %Y %m %d' -d "$arg")"
echo "year: $y / month: $m / day: $d"
done
Example:
$ ./parse.sh 2021-03 2021-03-14 3/14/19 11/2019
date: invalid date ‘2021-03’
year: / month: / day:
year: 2021 / month: 03 / day: 14
year: 2019 / month: 03 / day: 14
date: invalid date ‘11/2019’
year: / month: / day:
Any suggestions on how to handle the month/year combination correctly?
CodePudding user response:
#!/bin/bash
for arg
do
case $arg in
*-* ) IFS='-' read -r year month day ;;
*/*/*) IFS='/' read -r month day year ;;
*/* ) IFS='/' read -r month year day ;; # day is here for reset
esac <<< "$arg"
echo "year: $year / month: $month / day: $day"
done