標籤:
#!/bin/bashstartDate="$1"endDate="$2"DATE_FMT="%Y%m%d"source ./log.shexport DEBUG="true"function showUsage() { warn ""warn "------------------------ Usage ----------------------------- "warn " Syntax: checkInputDates.sh <start date> <end date>"warn ""warn " Remark: " warn " 1.Two arguments are required and must with format ‘YYYYmmDD‘."warn " 2.Named ‘end date‘ argument must be greater then or equal to ‘start date‘ argument."warn ""warn " Example: checkInputDates.sh 20140102 20140901" warn "------------------------------------------------------------ "}function checkDateValid() {local myDate=$1local exp="date +$DATE_FMT -d $myDate"if [ "$myDate" == "`$exp`" ]; thenecho "1"else echo "0"fi } function datesDiff() {local d1=`date +$DATE_FMT -d $1`local d2=`date +$DATE_FMT -d $2`local cr=$(($d1-$d2)); ##Diff in ‘day‘ unit.echo $cr}function compareDates() { local cr=$(datesDiff $1 $2); ##Diff in ‘day‘ unit.##debug "Compare: $(($(date +$DATE_FMT -d $1) - $(date +$DATE_FMT -d $2)));"; if [[ $cr -eq 0 ]]; then echo "0"elif [[ $cr -gt 0 ]]; thenecho "1"else echo "-1" fi}function toTomorrow() {local curDate=$1##debug "date -d ‘$curDate +1 day ‘ +$DATE_FMT"##echo `date -d "$curDate +1 day " +$DATE_FMT`echo $((`date +$DATE_FMT -d $curDate`+1))}###### Check inputs ################ #1. Only two arguments.warn ""if [ $# != 2 ]; thenwarn "ERROR: Only support two arguments input." | showUsage exit 1;fi #2. Check if they‘re the leagal value.tmpSd=$(checkDateValid $startDate) if [ "$tmpSd" == "0" ]; then ###It‘s the invalid date. eg: 20141901warn "ERROR: Invalid ‘start date‘ with input ‘$startDate‘, it must be with format ‘yyyyMMdd‘, eg: 20140101" | showUsageexit 1;fi tmpEd=$(checkDateValid $endDate) if [ "$tmpEd" == "0" ]; then ###It‘s the invalid date. eg: 20141901 warn "ERROR: Invalid ‘end date‘ with input ‘$startDate‘, it must be with format ‘yyyyMMdd‘, eg: 20140101" exit 1;fi#3. Check the arg2 greater than or equal arg1.##echo "Compare result: "$(compareDates $endDate $startDate)cprs=$(compareDates $endDate $startDate)echo "Diff days: $(datesDiff $endDate $startDate)."if [ "$cprs" == "-1" ]; thenwarn "ERROR: The first argument must not greater than the second one!" | showUsage exit 1;fi########################################loop the dates between start and end date.while [[ "$startDate" != "$endDate" ]]doecho $startDatestartDate=$(toTomorrow $startDate)done echo "---Input arguments---"echo "startDate:"$startDateecho "---Input arguments---"
在Shell中使用日期運算和比較