仅重试一次命令:当命令失败时(bash)

Retry a command only once : when a command fails (in 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

因为 "command 1" 相当大而且不仅仅是一个示例 echo 语句 here.I 不想添加 "command 1" 两次 .. 一次在 if 条件外,一次在 if 条件内。我希望这种逻辑以一种没有代码冗余的优化方式出现。

你可以像这样声明函数

function command
{
  your_command -f params

}

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

 do
   if command ; then 
      echo "success"
   else
      echo "retry"
      command
    fi

done

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

Siddhartha 关于使用函数的建议可能已经足够好了,但取决于实际 command 1(OP 提到它是 'quite big')我要唱反调并假设可能会有额外的将一些参数传递给函数的问题(例如,需要转义一些字符......??)。

一般的想法是有一个最多可以执行 2 次的内部循环,循环中的逻辑将允许 'early' 退出(例如,仅通过循环一次后) .

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

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