上篇总结了一些常用的函数,这篇写一个经常会用到的,与时间有关的应用场景:
给一个起始时间和结束时间,遍历中间的每一天,用于文件名组成部份。
直接上代码:
#!/bin/bash
# iterate day between begindate and enddate
#
get_seconds_by_date()
{
if [ "$1" ]; then
date -d "$1" +%s
else
date +%s
fi
}
get_date_by_seconds()
{
date -d "1970-01-01 UTC $1 seconds" +%Y%m%d
}
beginsec=$(get_seconds_by_date "$1")
endsec=$(get_seconds_by_date "$2")
curr=$beginsec
while [ $curr -le $endsec ];
do
get_date_by_seconds "$curr"
curr=$((curr+24*60*60))
done
测试命令
root@ADT:~# bash test.sh 2017-08-30 2017-09-30
20170830
20170831
20170901
20170902
20170903
20170904
20170905
20170906
20170907
20170908
20170909
20170910
20170911
20170912
20170913
20170914
20170915
20170916
20170917
20170918
20170919
20170920
20170921
20170922
20170923
20170924
20170925
20170926
20170927
20170928
20170929
20170930
#另一个简单的方法
#! /bin/sh
date=`date -d "+0 day $1" +%Y%m%d`
enddate=`date -d "+1 day $2" +%Y%m%d`
echo "------------------------------"
echo "date=$date"
echo "enddate=$enddate"
echo "------------------------------"
while [[ $date < $enddate ]]
do
echo $date
date=`date -d "+1 day $date" +%Y%m%d`
done
执行:./test.sh 2014-06-01 2014-06-06