在 Bash 中模拟 do-while 循环 [英] Emulating a do-while loop in Bash

查看:50
本文介绍了在 Bash 中模拟 do-while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Bash 中模拟 do-while 循环的最佳方法是什么?

What is the best way to emulate a do-while loop in Bash?

我可以在进入 while 循环之前检查条件,然后在循环中继续重新检查条件,但这是重复的代码.有没有更干净的方法?

I could check for the condition before entering the while loop, and then continue re-checking the condition in the loop, but that's duplicated code. Is there a cleaner way?

我的脚本的伪代码:

while [ current_time <= $cutoff ]; do
    check_if_file_present
    #do other stuff
done

如果在 $cutoff 时间之后启动,则不会执行 check_if_file_present,而 do-while 会.

This doesn't perform check_if_file_present if launched after the $cutoff time, and a do-while would.

推荐答案

两个简单的解决方案:

  1. 在 while 循环之前执行一次代码

  1. Execute your code once before the while loop

actions() {
   check_if_file_present
   # Do other stuff
}

actions #1st execution
while [ current_time <= $cutoff ]; do
   actions # Loop execution
done

  • 或者:

  • Or:

    while : ; do
        actions
        [[ current_time <= $cutoff ]] || break
    done
    

  • 这篇关于在 Bash 中模拟 do-while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆