Home > Enterprise >  Retrying bash command n times and sleeping m seconds in between
Retrying bash command n times and sleeping m seconds in between

Time:07-25

Bash script here.

I want to run a command that will output an integer 0 (0, 1, 2, 45, 193, etc.). I want to run it at least one time. If I run it the first time, and its output is 0, then the script can exit. If it is 1 then I want to keep running the same command over and over until it returns 0, and then like before, the script can exit. However:

  • I only want the command to be retried every 60 seconds; and
  • I only want the command retried a maximum of 10 times; after the 10th time if the command is still returning 1 then I want the script to exit with an error code (exit 1, etc.)

My best attempt thus far, inspired from a similar question here on SO:

# doSomething() returns 0 or higher
NEXT_WAIT_TIME=0
until [ $NEXT_WAIT_TIME -eq 10 ] || doSomething(); do
  $(( NEXT_WAIT_TIME   ))
  sleep 60
done

However when this runs, it doesn't actually check for comparison of the output for 0 vs. 1 and it executes 10 times immediately without sleeping in between tries. Can someone sport where I'm going awry? Thanks!

CodePudding user response:

This should do what you want:

#!/bin/bash

remaining_attemps=10

while (( remaining_attemps-- > 0 ))
do
    [[ $(doSomething) == 0 ]] && exit
    sleep 60
done

exit 1

Edit: Replying to OP comment.

You have a few options for running commands before exiting when doSomething outputs 0

1. Inside the while loop:
#!/bin/bash

remaining_attemps=10

while (( remaining_attemps-- > 0 ))
do
    if [[ $(doSomething) == 0 ]]
    then
        echo "doSomething = 0"
        exit
    fi
    sleep 60
done

exit 1
2. Outside the while loop:
#!/bin/bash

remaining_attemps=10

while (( remaining_attemps-- > 0 ))
do
    [[ $(doSomething) == 0 ]] && break
    sleep 60
done

(( remaining_attemps >= 0 )) || exit 1

echo "doSomething = 0"

  •  Tags:  
  • bash
  • Related