在Bash中模拟do-while循环

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

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

脚本的伪代码:

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

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

249833 次浏览

两个简单的解决方案:

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

    actions() {
    check_if_file_present
    # Do other stuff
    }
    
    
    actions #1st execution
    while [ current_time <= $cutoff ]; do
    actions # Loop execution
    done
    
  2. Or:

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

将循环体放在while之后和测试之前。while循环的实际主体应该是一个无操作。

while
check_if_file_present
#do other stuff
(( current_time <= cutoff ))
do
:
done

如果你觉得continue更易读,你可以使用continue代替冒号。你也可以插入一个只运行之间的迭代的命令(不是在第一个之前或最后一个之后),比如echo "Retrying in five seconds"; sleep 5。或在值之间打印分隔符:

i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'

我将测试改为使用双括号,因为您似乎在比较整数。在双方括号内,比较运算符(例如<=)是词法运算符,在比较2和10时会给出错误的结果。这些运算符不能在单个方括号内工作。

我们可以用while [[condition]]; do true; done在Bash中模拟一个do-while循环,如下所示:

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

举个例子。下面是我在bash脚本中获取ssh连接的实现:

#!/bin/bash
while [[ $STATUS != 0 ]]
ssh-add -l &>/dev/null; STATUS="$?"
if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done

它将按如下顺序给出输出:

Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' (git@github.com:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"

这个实现:

  • 没有代码重复
  • 不需要额外函数()
  • 不依赖于“while”中代码的返回值;循环的部分:
do=true
while $do || conditions; do
do=false
# your code ...
done

它也适用于read循环,跳过第一次读取:

do=true
while $do || read foo; do
do=false


# your code ...
echo $foo
done