LoginSignup
1

【シェルスクリプト】コマンドがエラーの場合に最大N回までリトライする処理

Posted at

最近シェルスクリプトを書くことが増えており、その中で書いたリトライ処理のコードについて残しておきます。

実現したい動作

  1. あるコマンドを実行する
  2. 異常終了(エラー発生)の場合はリトライ処理を行う
  3. リトライが指定した回数に達した or コマンドが正常終了した場合はリトライ終了

while文でリトライ

max_retry_count=3 # リトライ回数
retry_interval=5 # リトライ間隔(秒)

retry_count=0
while true; do
  # your_command -> 実行したいコマンド
  <your_command> && break

  # リトライ回数が上限に達している場合は、エラーメッセージを出力してリトライ終了
  retry_count=$((retry_count + 1))
  if [ $retry_count -eq $max_retry_count ]; then
    echo "Error: command failed after $max_retry_count attempts"
    break
  fi

  # 待機
  echo "Command failed. Retrying in $retry_interval seconds..."
  sleep $retry_interval
done

for文でリトライ

max_retry_count=3 # リトライ回数
retry_interval=5 # リトライ間隔(秒)

# your_command -> 実行したいコマンド
<your_command>

# リトライ処理の実装
if [ $? != 0 ]; then
  for retry_num in $(seq 1 $max_retry_count)
  do
    # 待機
    echo "Command failed. Retrying in $retry_interval seconds..."
    sleep $retry_interval

    # コマンドが正常に終了した場合は、ループを終了
    <your_command> && break

    # リトライ回数が上限に達している場合は、エラーメッセージを出力
    if [ $retry_num -eq $max_retry_count ]; then
      echo "Error: command failed after $max_retry_count attempts"
    fi
  done
fi

補足解説

ここで、

<your_command> && break

の部分についてですが、実行している処理は下記と同義です。

<your_command>

if [ $? -eq 0 ]; then
  break
fi

bashシェルスクリプトでは && によって複数コマンドのAND演算が可能であり、例えば、

command1 && command2

というコードは、"command1"が成功したら"command2"を実行するという処理になります(参考:【Linux】シェルスクリプトにおける && と || の違い)。

よって、&&の後ろにbreakを書いておくことで、<your_command>が成功した場合のみループを抜ける、という処理が可能になります。

以上。

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
What you can do with signing up
1