仿效猛砸一个do-while循环

问题描述 投票:111回答:3

什么是仿效猛砸一个do-while循环的最佳方式?

我可以检查进入while循环之前的状态,然后再继续重新检查循环的条件,但是这重复的代码。是否有一个更清洁的方式?

我的脚本的伪代码:

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

如果check_if_file_present时间后推出此不执行$cutoff,和一个做,而会。

bash loops do-while
3个回答
193
投票

两个简单的解决方案:

  1. while循环之前执行一次你的代码 actions() { check_if_file_present # Do other stuff } actions #1st execution while [ current_time <= $cutoff ]; do actions # Loop execution done
  2. 要么: while : ; do actions [[ current_time <= $cutoff ]] || break done

134
投票

请将您的循环体的while之后和测试之前。在while循环的实际机构应当是一个空操作。

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

取而代之的是结肠,你可以,如果你找到更易读使用continue。您还可以插入一个命令,将只迭代之间运行(不是之前姓氏或之后),如echo "Retrying in five seconds"; sleep 5。值之间的或打印的分隔符:

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

我改变了测试,因为你似乎比较整数使用双括号。内双方括号中,比较运算符如<=是词汇和比较2和10时,例如将给出错误的结果。这些运营商不要单方括号内工作。


6
投票

取而代之的是结肠,您可以继续使用,如果你发现更易读

这种方法模仿这样做时,虽然方式循环,即我一直在寻找 - 有行动后的状态测试。我还发现,我可以将索引增量(如果需要)do语句之后,而不是continue语句。

while 
    check_if_file_present
    #do other stuff
    (( current_time <= cutoff ))
do
    (( index++ ));
done

0
投票

我们可以仿效猛砸一个do-while循环,像这样while [[condition]]; do true; done

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

举一个例子。这是我在得到在bash脚本ssh connection实现:

#!/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' ([email protected]: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"
© www.soinside.com 2019 - 2024. All rights reserved.