0

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.

Here is a short version of my script:

CleanUp() {
    echo "Trap exit detected"
    rm -f $TMPFILE1
    rm -f $TMPFILE2
    StopPreventSleep
    echo "... and ready!" && 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
    ;;

I want that the script only could exit after doing [somemagic] in each loop (depends on the parameter $1 = which case is choosen).

UsersUser
  • 175
  • 2
  • 14

1 Answers1

2

change the line

echo "... and ready!" && exit

to:

QUIT=1

And after each of your [somemagic], add the some extra logic as below:

...
[somemagic]
if [ ! -z $QUIT ]; then
   exit
fi
Robin Hsu
  • 4,164
  • 3
  • 20
  • 37
  • That´s the right hint - I declare two functions. One for the trap definition `QUIT=1` the other for the real clean up process. The trap will execute the first function and the second function will be execute at the end of the loop. – UsersUser Nov 07 '14 at 10:40
  • ... but it will interrupt the running command like I described in http://stackoverflow.com/questions/26808727/bash-trap-interrupt-command-but-should-exit-on-end-of-loop – UsersUser Nov 12 '14 at 08:06