bash - 仅重试一次命令:当命令失败时(在 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 可能需要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
推荐阅读
- jenkins - 具有奇数资源编号的 Kubernetes Jenkins 从站
- r - 在计算序列的正态分布时,如何在 R 中设置 dnorm 的步长?
- vb.net - FoxPro 命令到 VB.NET
- reactjs - 在 React 中,是否允许多次使用 props.children 元素?
- javascript - 通过异步函数解决承诺返回
- sugarcrm - 在弹出窗口中显示字段为 NULL 的记录
- google-cloud-platform - 导入图像时发生“标签已经是基本事实”
- sql-server - SQL Server 使用 LIKE 查找带重音的拉丁词
- firebase - 使用“将集合导出到 BigQuery”扩展程序生成架构视图:fs-bq-schema-views
- c# - 从 versin 2.2 更新后,Asp.Net Core 3.1 中的本地化不起作用