如何在bash脚本中实现ctrl c处理以便脚本中断,以及脚本启动当前运行的命令?
(想象一下,有一个脚本执行一些长时间运行的命令.用户点击ctrl c并中断命令,但脚本继续执行.)我需要它以一种他们都被杀死的方式行事.
您可以通过创建在接收到SIGINT时要调用的子例程来执行此操作,并且需要运行陷阱’子例程’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