【问题标题】:How to continue bash loop?如何继续bash循环?
【发布时间】:2020-05-25 13:23:31
【问题描述】:

我目前面临一个我无法解决的问题。在 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

输出的第一部分是正确的。循环经历了几天并显示了消息。但在满足错误条件后,循环不会返回检查语句。 输出

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

为什么“继续”不起作用?

【问题讨论】:

    标签: bash macos algorithm loops


    【解决方案1】:

    您忘记在其他部分更新 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2015-09-24
      • 1970-01-01
      • 2018-03-20
      • 2021-03-25
      • 2020-12-26
      相关资源
      最近更新 更多