[Linux] Sample Code to Retry Shell Commands Until Success

Tadashi Shigeoka ·  Thu, May 19, 2022

I’ll introduce sample code to retry commands until success in Linux /bin/sh.

Linux | リナックス

Prerequisites: Debian + /bin/sh

  • OS: Debian Buster
  • Execute interactive /bin/sh commands with Amazon ECS Exec

Sample Code to Retry Commands Until Success: /bin/sh Edition

NEXT_WAIT_TIME=0
COMMAND_STATUS=1
while [ $COMMAND_STATUS -ne 0 ]; do
  command # exec your command
  COMMAND_STATUS=$?
  sleep $NEXT_WAIT_TIME
  NEXT_WAIT_TIME=$((NEXT_WAIT_TIME+1))
  echo $NEXT_WAIT_TIME
done

Above, I wanted to retry commands until success in Linux /bin/sh.

That’s all from the Gemba.

Reference Information