2

I have a while loop in this form:

while :; do
   performTask1 || break
   performTask2 || break
   performTask3 || break
   ...
   performTaskX || break
done

Basically, I want to break out of the loop whenever one of the tasks errors out. Is there a better way to achieve this?

I suppose another way to do this is:

while :; do
   performTask1 && performTask2 ... && performTaskX || break
done

However, this still looks ugly to me.

0

Essentially you are saying that if a task fails then the subsequent tasks should not execute. There is no need to break, just make the tasks dependent on the successfull completion of preceding tasks:

while
  performTask1 &&
  performTask2 &&
  ...
  performTaskX-1 &&
  performTaskX
do :; done

There is no need to put all tasks on one line... This form does not look ugly to my eyes.

  • But this will continue the while loop, wouldn't it? It will just start from the beginning again. I need to get out of the loop if anything fails. – Alberto Rivera Nov 18 '16 at 1:37
  • I have edited the code to account for the need to stop the loop when a task fails. – AlexP Nov 18 '16 at 2:08
  • However, I would still use the code arranged as in your initial example, because it makes it easy to see that any task failing breaks the loop. After all, beauty is in the eye of the beholder. – AlexP Nov 18 '16 at 2:14
  • Yep, I think there's no easy way to break out. Thank you anyways. – Alberto Rivera Nov 18 '16 at 18:07
0
set -e
while :; do
   performTask1
   performTask2
   performTask3
   ...
   performTaskX
done
set +e

This will exit your entire script if there is any error.

If this isn't the last part of your script, you could instead use:

while performTask1 &&
    performTask2 &&
    performTask3 &&
    ... &&
    performTaskX
do
  :
done

Also see:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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