Bash陷阱-仅在循环结束时退出 [英] Bash trap - exit only at the end of loop

查看:77
本文介绍了Bash陷阱-仅在循环结束时退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,它有不同的情况-每个都有一个for或while循环.我已经声明了一个陷阱函数,以获得退出脚本和循环的机会.但是,如果这样做,脚本将立即退出-我想在循环运行结束时退出循环,因为每次循环运行都需要很长时间.

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
    ;;

我希望脚本只能在每个循环中执行[somemagic]后退出(取决于参数$1 =选择哪种情况).

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

推荐答案

更改行

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

收件人:

QUIT=1

在每个[somemagic]之后,添加一些额外的逻辑,如下所示:

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

...
[somemagic]
if [ ! -z $QUIT ]; then
   exit
fi

这篇关于Bash陷阱-仅在循环结束时退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆