LoginSignup
31
21

More than 5 years have passed since last update.

bash で コマンドが成功するまでリトライする

Last updated at Posted at 2016-03-26

ここにいろいろ載ってました。

回答1

NEXT_WAIT_TIME=0
COMMAND_STATUS=1
until [ $COMMAND_STATUS -eq 0 || $NEXT_WAIT_TIME -eq 4 ]; do
  command
  COMMAND_STATUS=$?
  sleep $NEXT_WAIT_TIME
  let NEXT_WAIT_TIME=NEXT_WAIT_TIME+1
done

リトライ間隔を0秒、1秒、2秒… と増やしながら実行する感じですね。
ただ、これだと、2回めで成功してもsleepしちゃうな、とか、最終的に全部失敗した際、無駄に最後にsleepだけして終了するな、とか気になりました。

回答2


NEXT_WAIT_TIME=0
until command || [ $NEXT_WAIT_TIME -eq 4 ]; do
   sleep $(( NEXT_WAIT_TIME++ ))
done

こっちの方がシンプルで良さそう。

あと、こんなのもあった。

その他

#!/bin/bash

# Retries a command on failure.
# $1 - the max number of attempts
# $2... - the command to run
retry() {
    local -r -i max_attempts="$1"; shift
    local -r cmd="$@"
    local -i attempt_num=1

    until $cmd
    do
        if (( attempt_num == max_attempts ))
        then
            echo "Attempt $attempt_num failed and there are no more attempts left!"
            return 1
        else
            echo "Attempt $attempt_num failed! Trying again in $attempt_num seconds..."
            sleep $(( attempt_num++ ))
        fi
    done
}

# example usage:
retry 5 ls -ltr foo

実際使うときには、timeout コマンドと組み合わせて、◯秒以内に終わらなかったら、再実行 みたいな感じかな。

31
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
21