Ctrl-C在bash脚本中

如何在bash脚本中实现ctrl + c处理,以便脚本中断,以及脚本启动的当前正在运行的命令?

(想象一下,有一个脚本执行一些长时间运行的命令,用户点击ctrl + c并中断命令,但脚本继续执行)。我需要它的行为方式,它们都被杀死。

您可以通过创build一个您希望在接收到SIGINT时调用的子例程,并且需要运行trap 'subroutinename' INT

例:

 #!/bin/bash int_handler() { echo "Interrupted." # Kill the parent process of the script. kill $PPID exit 1 } trap 'int_handler' INT while true; do sleep 1 echo "I'm still alive!" done # We never reach this part. exit 0