Skip to main content

Trigger a non-zero exit code when I break out of a loop [Resolved]

I'd like to run a series of tasks but stop should any of them fail, hence I've written (something like):

for task in [TASKS]; do
  process "$task" || break
  commit "$task"

This works fine, but (as specified) the exit status of this loop is zero even if we break early. Ideally break-ing would be able to convey the failure.

I know returning 0 is the documented behavior of break, but I'm curious if there are any relatively clean workarounds. The best I can imagine is wrapping this in a function and setting a didBreak variable, and using that as the exit status (of the function). It'd work, but it feels overly-complex.

Question Credit: dimo414
Question Reference
Asked September 21, 2019
Posted Under: Unix Linux
3 Answers

My imagined solution is:

run_til_failure() {
  local didBreak=0
  for task in [TASKS]; do
    process "$task" || { didBreak=1; break; }
    commit "$task"
  local loopExit=$?
  if (( loopExit )); then return $loopExit; fi
  return $didBreak

credit: dimo414
Answered September 21, 2019
Your Answer