我想存储两个用户输入日期之间的所有可能的日期。输入将类似于20140605和20140830。
我想使用循环将给定日期之间的每个日期存储到一个变量中,以便可以使用它。
生成或计算的日期必须与输入的格式相同。
startdate=20141030
starttime=165800
enddate=20141120
endtime=175050
day=`expr $startdate % 100`
month=`expr $startdate % 10000`
year=`expr $startdate % 100000000`
month=`expr $month / 100`
year=`expr $year / 10000`
echo "$year $month $day"
while [ $enddate -ge $cdate ]
do
var=$cdate
#using variable var
if [ $day -eq 31 ]; then
cdate=`expr $cdate - $day`
day=1
((month++))
cdate=`expr $cdate + 100 + $day`
#cdate=`expr $cdate + $day`
if [ $month -eq 13 ]; then
#tmp=`expr $month \* 100`
cdate=`expr $cdate - $month \* 100`
month=1
((year++))
cdate=`expr $cdate + 10100`
if [ $year -eq 2999 ]; then
((year++))
echo $cdate
cdate=30010100
fi
fi
else
((day++))
((cdate++))
fi
if [ $enddate == $cdate ]; then
check=1
fi
done
我试图以此方式实现我的要求。但是在编译时它说:
一元运算符预期
导致此错误的原因是什么,如何使用Shell脚本以更好的方式执行此操作?
我将采取完全不同的方法。手动进行所有日期计算很容易出错(一个月中不一定总是有31天,您会有leap年,等等)。再看一下代码,很难说出自己在做什么(这是一件很糟糕的事情)。
#!/bin/bash
startdate=20141030
enddate=20141120
dates=()
for (( date="$startdate"; date != enddate; )); do
dates+=( "$date" )
date="$(date --date="$date + 1 days" +'%Y%m%d')"
done
echo "${dates[@]}"
这使用date
命令来处理所有计算,并将每个日期存储在$dates
数组中。
结果看起来像这样:
20141030 20141031 20141101 20141102 20141103 20141104 20141105 20141106 20141107 20141108 20141109 20141110 20141111 20141112 20141113 20141114 20141115 20141116 20141117 20141118 20141119
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句