仅重试命令一次:当命令失败时(在 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 条件内。我希望以优化的方式使用此逻辑,没有代码冗余。

根据评论,听起来 OP 可能需要为给定的$i值调用多达 2 次command 1,但只想在脚本中键入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

你可以声明这样的函数

function command
{
your_command -f params
}
for ( i=3; i<5; i++)
do
if command ; then 
echo "success"
else
echo "retry"
command
fi
done

最新更新