1

I need to execute a command and also check if it was successful. If there was an error, I should try again and the following code is working as expected.

But what if I need to try the same command 3 or 4 times till it gets successfully executed? The if / else clause will become pretty complicated.

some command

if [ $? -eq 0 ];then
echo "success"
else 

echo "failed first attempt trying again"

some command

if [ $? -eq 0 ];then
echo "success in second attempt"
else
echo "failed second attempt"
fi

fi

Is there better way to write a script that will try the command 4 times before quitting?

shantanuo
  • 3,579
  • 8
  • 49
  • 66

2 Answers2

11

Use a loop to execute /usr/local/some/command a number of times dictated by MAX_TRIES. If all attempts at execution are unsuccessful it will error with code $ERR. If it is sucessful, it will exit 0 immediately, and break out of the loop.

#!/bin/bash

ERR=1 # or some non zero error number you want
MAX_TRIES=4 
COUNT=0
while [  $COUNT -lt $MAX_TRIES ]; do
   /usr/local/some/command
   if [ $? -eq 0 ];then
      exit 0
   fi
   let COUNT=COUNT+1
done
echo "Too many non-successful tries"
exit $ERR

If you prefer you could use a c style for loop

 #!/bin/bash
 ERR=1 # or some non zero error number you want
 MAX_TRIES=4

 for (( i=1; i<=$MAX_TRIES; i++ ))
   do
     /usr/local/some/command
     if [ $? -eq 0 ];then
        exit 0
     fi
   done
echo "Too many non-sucessful tries"
exit $ERR
Sirch
  • 5,785
  • 4
  • 20
  • 36
  • In spirit of the comments on my answer: just adding a code snippet without any commentary, employing but not naming what is used (the loop) isn't really substantial. – Roman Jul 09 '13 at 11:43
  • @Roman: Yes, it is. It explains how to use a while loop in bash in terms an experienced user can benefit from: Code. It will be enough to continue without looking up further linked resources that might or might not exist in the future. – Sven Jul 09 '13 at 11:46
  • Fair comment, anything particular you would like me to explain? – Sirch Jul 09 '13 at 11:47
  • @SvW An experienced user would now about the while loop?! for chriss...Anyway, it's quite ok now and I refrained from a downvote to begin with, the nice guy I am. >:/ Sirch: Yeah, maybe explain that a while loop is used. – Roman Jul 09 '13 at 11:50
0

I really can't wonder enough how you cannot know about the while loop.

Edit. As requested by your friendly moderators, have some drop-in, substantial bash cake. Yay, cake!

while [ $w_count -lt $w_maxtries ]; do
   some command
   if [ $? -ne 0 ]; then
      # cmd failed
      let w_count=w_count+1
      # optional, consider redirecting to STDERR.
      echo "Warning, command failed the ${w_count}th time!"
      if [[ $w_count -ge $(( $w_maxtries - 1 )) ]]; then
        # whoops too many tries
        echo "Giving up"
        exit 1
      fi
   else
      # Yay it worked
      break
   fi
done
# continue here.
Roman
  • 3,907
  • 3
  • 21
  • 34
  • Roman, while links to reference material are a great thing, we do encourage answers not to be solely made of links. Perhaps you might give a small example of the use of the loop? – MadHatter Jul 09 '13 at 11:33
  • Hey, he claims to have 15 years of IT exp under his belt, he should be fine. And I prefer people to come to their own conclusions after a gentle (ok maybe not alway so gentle, i'll admit) nudge. This is of more use. But i'll keep your suggestion in mind the next time. – Roman Jul 09 '13 at 11:36
  • Downvote for link-only answer. If you want to provide only a link, write a comment. – Sven Jul 09 '13 at 11:38
  • 3
    It's not for the questioner's benefit that we make the request - it's because externally-linked material can change, move, or disappear over time, rendering useless an answer that contains nothing but links. An answer that is substantive stays useful for much longer. – MadHatter Jul 09 '13 at 11:38
  • Have some cake, and consider your votes on both posts where applicable. – Roman Jul 09 '13 at 12:00
  • There is no reason to get worked up about this and get all competitive. Neither MadHatter nor I are mods, and by the way, we all know the cake is a lie :) – Sven Jul 09 '13 at 12:07
  • Not competitive nor worked up, just disagreement and resignation about gross inconsistencies in human behaviour. – Roman Jul 09 '13 at 12:17