例如今天是 06/04/2018;期望的输出是 05/31/2018。
对于 07/01/2018,输出应为 06/29/2018。
答案1
查找最后一个工作日(假设工作周是周一到周五),输出上个月的最后3天(降序),并找到第一个非周末日
for m in {1..12}; do
firstMonthDay="2018-$m-01"
for i in {1..3}; do
read dow date <<<"$(date -d "$firstMonthDay - $i days" "+%u %c")"
if [[ $dow -le 5 ]]; then
echo $date
break
fi
done
done
Fri Dec 29 00:00:00 2017
Wed Jan 31 00:00:00 2018
Wed Feb 28 00:00:00 2018
Fri Mar 30 00:00:00 2018
Mon Apr 30 00:00:00 2018
Thu May 31 00:00:00 2018
Fri Jun 29 00:00:00 2018
Tue Jul 31 00:00:00 2018
Fri Aug 31 00:00:00 2018
Fri Sep 28 00:00:00 2018
Wed Oct 31 00:00:00 2018
Fri Nov 30 00:00:00 2018
在我使用的地方调整您想要的输出日期格式%c
我使用该月的最后 3 天,因为这是我们最需要迭代的天:31 号星期日、30 号星期六、29 号星期五。
我们封装成一个函数:
lastWorkdayPreviousMonth() {
local first fmt dow date i opt OPTIND=1
while getopts :d:f: opt; do
case $opt in
d) first=$OPTARG ;;
f) fmt=$OPTARG ;;
esac
done
: ${first:=$(date "+%Y-%m-01")} ${fmt:="%c"}
for i in {1..3}; do
read dow date <<<"$(date -d "$first- $i days" "+%u $fmt")"
if [[ $dow -le 5 ]]; then
echo $date
break
fi
done
}
然后
$ lastWorkdayPreviousMonth
Thu May 31 00:00:00 2018
$ for m in {1..12}; do lastWorkdayPreviousMonth -f "%d/%m/%Y" -d 2018-$m-01; done
29/12/2017
31/01/2018
28/02/2018
30/03/2018
30/04/2018
31/05/2018
29/06/2018
31/07/2018
31/08/2018
28/09/2018
31/10/2018
30/11/2018
答案2
下面一行将打印上个月的最后一个工作日。
day=`date -d "$(date +%m/01/%Y) -1 day" | awk '{print $1}'`; if [ $day == Sat ]; then D=`date -d "$(date +%m/01/%Y) -2 day" "+%m/%d/%Y"`;echo $D; elif [ $day == Sun ]; then D=`date -d "$(date +%m/01/%Y) -3 day" "+%m/%d/%Y"`;echo $D; else D=`date -d "$(date +%m/01/%Y) -1 day " "+%m/%d/%Y"`;echo $D; fi
排序代码:
day=`date -d "$(date +%m/01/%Y) -1 day" | awk '{print $1}'`;
if [ $day == Sat ]; then
D=`date -d "$(date +%m/01/%Y) -2 day" "+%m/%d/%Y"`;
echo $D;
elif [ $day == Sun ]; then
D=`date -d "$(date +%m/01/%Y) -3 day" "+%m/%d/%Y"`;
echo $D;
else
D=`date -d "$(date +%m/01/%Y) -1 day " "+%m/%d/%Y"`;
echo $D;
fi