首页 > 解决方案 > 仅重试一次命令:当命令失败时(在 bash 中)

问题描述

 for ( i=3; i<5; i++)

 do

   execute some command 1

   if command 2 is successful then do not run the command 1 (the for loop should continue)

   if command 2 is not successful then run command 1 only once (like retry command 1 only once, after this the for loop should continue)    

done

这里要注意命令2依赖于命令1,命令2只能在命令1之后执行

例如:

 for ( i=3; i<5; i++)
 do
    echo "i" >> mytext.txt   ---> command 1 
    if "check the content of mytext.txt file to see if the value of i is  actually added" ---> command 2  
    if it is not added then execute echo "i" >> mytext.txt (command 1) again and only once.
    if i value is added to the file .. then exit and continue the loop
  done

由于“命令 1”非常大,而不仅仅是此处的示例 echo 语句。我不想添加两次“命令 1”......一次在 if 条件之外,一次在 if 条件内。我希望这种逻辑以一种优化的方式,没有代码冗余。

标签: bashloopsretry-logic

解决方案


根据评论,听起来 OP 可能需要command 1为给定值调用多达 2 次$i,但只想command 1在脚本中键入一次。

悉达多关于使用函数的建议可能已经足够好,但取决于实际情况command 1(OP 提到它“相当大”),我将扮演魔鬼的拥护者并假设将一些参数传递给函数可能会出现其他问题(例如,需要转义一些字符... ??)。

一般的想法是有一个最多可以执行2次的内部循环,循环中的逻辑将允许“提前”退出(例如,在仅通过循环一次之后)。

由于我们使用的是伪代码,我将使用相同的...

for ( i=3; i<5; i++ )
do
    pass=1                                    # reset internal loop counter

    while ( pass -le 2 )
    do
        echo "i" >> mytext.txt                # command 1

        if ( pass -eq 1 )                     # after first 'command 1' execution
        && ( value of 'i' is in mytext.txt )  # command 2
        then
            break                             # break out of inner loop; alternatively ...
        #   pass=10                           # ensure pass >= 2 to force loop to exit on this pass
        fi

        pass=pass+1                           # on 1st pass set pass=2 => allows another pass through loop
                                              # on 2nd pass set pass=3 => will force loop to exit
    done
done

推荐阅读