[英]How to continue bash loop?
我目前面临一个我无法解决的问题。 在 Mac OS Catalina 上编写 bash 脚本。 循环通过真话陈述,但在面对错误陈述后,它坚持下去。
任务%Do something%如果循环中的当前日期是工作日。
代码
# Set initial dates
starting_date=2020-02-10
ending_date=2020-02-24
current_date=$starting_date
#What is the day of the week of this day
current_date_wd=$(date -j -f "%Y-%m-%d" "$current_date" +%u )
#Loop in the set date range
while [ "$current_date" != "$ending_date" ];
do
if [ "$current_date_wd" != "6" ] && [ "$current_date_wd" != "7" ]
then
# Echo the current workday
echo 'Today is '$current_date' and it-s a '$current_date_wd'-s day'
# Increment by 1d
current_date=`date -j -v +1d -f "%Y-%m-%d" "$current_date" +%Y-%m-%d`
# Calculate day of week
current_date_wd=$( date -j -f "%Y-%m-%d" "$current_date" +%u )
else
# Increment
current_date=`date -j -v +1d -f "%Y-%m-%d" "$current_date" +%Y-%m-%d`
# Skip
echo 'skip'
continue
fi
done
输出的第一部分是正确的。 循环经过这些日子并显示消息。 但是在满足 false 条件之后,循环不会返回检查语句。 输出
Today is 2020-02-10 and it-s a 1-s day
Today is 2020-02-11 and it-s a 2-s day
Today is 2020-02-12 and it-s a 3-s day
Today is 2020-02-13 and it-s a 4-s day
Today is 2020-02-14 and it-s a 5-s day
skip
skip
skip
skip
skip
skip
skip
skip
skip
预期的
Today is 2020-02-10 and it-s a 1-s day
Today is 2020-02-11 and it-s a 2-s day
Today is 2020-02-12 and it-s a 3-s day
Today is 2020-02-13 and it-s a 4-s day
Today is 2020-02-14 and it-s a 5-s day
skip
skip
Today is 2020-02-17 and it-s a 1-s day
Today is 2020-02-18 and it-s a 2-s day
Today is 2020-02-19 and it-s a 3-s day
Today is 2020-02-20 and it-s a 4-s day
Today is 2020-02-21 and it-s a 5-s day
skip
skip
为什么“继续”不起作用?
您忘记在其他部分更新current_date_wd ,这是有效的解决方案。
starting_date=2020-02-10
ending_date=2020-02-24
current_date=$starting_date
#What is the day of the week of this day
current_date_wd=$(date -j -f "%Y-%m-%d" "$current_date" +%u )
#Loop in the set date range
while [ "$current_date" != "$ending_date" ];
do
if [ "$current_date_wd" != "6" ] && [ "$current_date_wd" != "7" ]
then
# Echo the current workday
echo 'Today is '$current_date' and it-s a '$current_date_wd'-s day'
# Increment by 1d
current_date=`date -j -v +1d -f "%Y-%m-%d" "$current_date" +%Y-%m-%d`
# Calculate day of week
current_date_wd=$( date -j -f "%Y-%m-%d" "$current_date" +%u )
else
# Increment
current_date=`date -j -v +1d -f "%Y-%m-%d" "$current_date" +%Y-%m-%d`
current_date_wd=$( date -j -f "%Y-%m-%d" "$current_date" +%u )
# Skip
echo 'skip'
continue
fi
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.