我正在寻找一个很好的干净的方法来实现bash中的重试循环机制。
以下是工作原理:

retries = 3
while retries:
    cmd1
    cmd2
    cmd3
    if not_error:
        break
    echo "something went wrong, let's wait 60 seconds and retry"
    sleep 60
    retries --
if retries = 0:
    exit "Failed!"

每个命令都可能失败,我希望停止运行下一个命令,只运行重试代码。

最佳答案

像这样的:

#!/bin/bash

retries=3

for ((i=0; i<retries; i++)); do
    cmd1 && cmd2 && cmd3
    [[ $? -eq 0 ]] && break

    echo "something went wrong, let's wait 60 seconds and retry"
    sleep 60
done

[[ $retries -eq i ]] && { echo "Failed!"; exit 1; }

09-28 01:16