Bash 捕捉SIGINT或Ctl + C

示例

陷阱会为子shell重置,因此sleep仍然会作用于(通常是通过退出)SIGINT发送的信号^C,但父进程(即shell脚本)不会。

#!/bin/sh

# Run a command on signal 2 (SIGINT, which is what ^C sends)
sigint() {
    echo "杀死了子壳!"
}
trap sigint INT

# Or use the no-op command for no output
#trap : INT

# This will be killed on the first ^C
echo "Sleeping..."
sleep 500

echo "Sleeping..."
sleep 500

还有一个变体,它仍然允许您通过^C每秒按下两次来退出主程序:

last=0
allow_quit() {
    [ $(date +%s) -lt $(( $last + 1 )) ] && exit
    echo "Press ^C twice in a row to quit"
    last=$(date +%s)
}
trap allow_quit INT