Bash trap - exit only at the end of loop

2019-09-17 08:27发布

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).

标签: bash shell loops
1条回答
叼着烟拽天下
2楼-- · 2019-09-17 09:00

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
查看更多
登录 后发表回答