Ctrl+C 打破无限循环,然后在 Bash 脚本中在循环外执行某些操作而不退出?

Ctrl+C 打破无限循环,然后在 Bash 脚本中在循环外执行某些操作而不退出?

我读了很多答案,他们都只是建议终止脚本或将其发送到后台等。我想要的是

虽然 true 确实

某物...

如果(按下 ctrl+c 则中断)

完成回应“退出循环”

因为按下了 ctrl+c,所以我处于循环之外,所以我可以在这里做其他事情而不必退出脚本......

而且这个问题不是重复的,因为我搜索了几个小时,没有答案能满足我的要求。那个“Out of the loop”永远不会被打印出来,我尝试了各种答案中的很多例子!

信息:我使用(1)Scientific Linux SL 版本 5.4(Boron),(2)Ubuntu 16.04

编辑:我希望这个精确的代码能够工作

#!/bin/bash

loopN=0

while true
do

echo "Loop Number = $i"
i=$(($i+1))

#I want to break this loop when Ctrl+C is pressed

done

#Ctrl+C has been pressed so I am outside the loop going to do something..

echo "Exited the loop, there were $i number of loopsexecuted !"
#here I will execute some commands.. let's say date
date

#and then I will exit the script

答案1

#!/bin/bash

#function called by trap
do_this_on_ctrl_c(){
    echo "Exited the loop, there were $i number of loops executed !"
    date
    exit 0
}

trap 'do_this_on_ctrl_c' SIGINT

loopN=0

while true
do
    echo "Loop Number = $i"
    i=$(($i+1))
done

相关内容