【发布时间】:2022-08-18 20:10:36
【问题描述】:
如何在 Linux shell 脚本中计算任何一个月的星期一数?
-
你试过什么?它是如何失败的?
-
除非您考虑这种作弊:使用
cal命令并以合适的方式解析输出。
如何在 Linux shell 脚本中计算任何一个月的星期一数?
cal 命令并以合适的方式解析输出。
以下代码显示了如何
“Linux shell 脚本中任何一个月的星期一数”
可以实现:
# Choose the year in the following line
export year=2021
export month=1
while [ "$month" -lt 13 ]
do
export day=1;
export count=0;
while [ "$day" -lt 32 ]
do
export anydate="$year""-""$month""-""$day"
date "+%Y-%m-%d" -d "$anydate" > /dev/null 2>&1
if [ $? == 0 ] # check if date is valid
then
#--- following line is for debugging only
#echo $anydate
export weekday=`date -d $anydate +"%u"`
if [ $weekday == 1 ]
then
export count=`expr $count + 1`
fi
fi
export day=`expr $day + 1`
done
echo $year month $month Monday count $count
export month=`expr $month + 1`
done
年度产出 = 2021:
2021 month 1 Monday count 4
2021 month 2 Monday count 4
2021 month 3 Monday count 5
2021 month 4 Monday count 4
2021 month 5 Monday count 5
2021 month 6 Monday count 4
2021 month 7 Monday count 4
2021 month 8 Monday count 5
2021 month 9 Monday count 4
2021 month 10 Monday count 4
2021 month 11 Monday count 5
2021 month 12 Monday count 4
一条关键线是
export weekday=`date -d $anydate +"%u"`
它写了工作日的编号,其中 1 表示星期一。
如果任何其他行需要更多描述,请在评论中告诉我们。
【讨论】: