Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am looking to write a small korn shell script doing 5 tests (by waiting some time before each one) and then, if they all fail, performing an action.

I was looking at doing something like :

    for i in {1..5}
    do
       "doMyTest"             #it fills a variables "status" (but can unfortunately fails)
       if [ "$status" ]; then #if status is filled then we can leave the loop
          break
       fi
       sleep 3                #else wait some time before doing another try
    done

    if [ -z "$status" ]; then
       exit 1
    fi

... then the rest of my program

Do you have any idea how could I do this in a better way ? It sounds a bit redundant ...

share|improve this question
    
can you explain why is not correct? with the current implementation after a max of 5 "failed" executions it ends. –  BitsOfNix May 21 at 12:46
    
Actually, my code is bigger than just this test, I have many more lines after. But I want them to be only executed if the status has been retrieved in 5 tries. –  user1058398 May 21 at 13:42
    
That's more or less how I'd do it. Set a flag within the loop, then check that flag outside the loop. –  glenn jackman May 21 at 16:30
    
I don't understand what you want to do. Run some code if all 5 iterations of the loop were executed? Run some code if the loop broke out early? Exit the script if doMyTest fails? –  Gilles May 21 at 23:41
    
Also appears on SO –  Henk Langeveld May 22 at 10:46

1 Answer 1

You could avoid to double-check $status by doing it like this:

for i in {1..5}
do
   "doMyTest"                 #it fills a variables "status" (but can unfortunately fails)
   if [ -n "$status" ]; then  #if status is filled then we can leave the loop
      break
   elif [ $i -eq 5 ]; then
       exit 1                 #all the tests failed, exiting
   fi
   sleep 3                    #else wait some time before doing another try
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.