title: Bash trap - exit only at the end of loop
body: <p>I´ve got a bash script which has different cases - each with a for or a while loop. I´ve declared a trap function to get the chance to exit the script and the loop. But if I do this the script will exit immediately - I want to exit the loop at the end of the loop run because each loop run takes a long time.</p>
  
  <p>Here is a short version of my script:</p>
  
  <pre><code>CleanUp() {
      echo "Trap exit detected"
      rm -f $TMPFILE1
      rm -f $TMPFILE2
      StopPreventSleep
      echo "... and ready!" &amp;&amp; exit
  }
  trap CleanUp EXIT INT TERM SIGINT SIGTERM SIGTSTP
  case $1 in
     check)
            for FILES in "${SRCFILES[@]}"
            do
              [somemagic]
            done
      ;;
      read)
            for FILES in "${SRCFILES[@]}"
            do
              [somemagic]
            done
      ;;
      write)
            while [ -n "$line" ]
            do
              [somemagic]
            done
      ;;
  </code></pre>
  
  <p>I want that the script only could exit after doing [somemagic] in each loop (depends on the parameter <code>$1</code> = which case is choosen).</p>