捕獲 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