捕获 SIGINT 或 CtlC

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

#!/bin/sh

# Run a command on signal 2 (SIGINT, which is what ^C sends)
sigint() {
    echo "Killed subshell!"
}
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