在bash中,如何在不停止脚本的情况下捕获和处理SIGINT?

lox*_*axs 2 bash signals sigint

看起来像

trap on_sigint SIGINT
Run Code Online (Sandbox Code Playgroud)

一旦SIGINT被抓住就停止脚本.然后,on_sigint执行.是否可以在SIGINT不停止脚本的情况下处理?

tha*_*guy 6

SIGINT处理程序运行后不会终止脚本.这是一个小型的自包含测试用例:

trap on_sigint SIGINT
on_sigint() { echo "caught"; }

{ sleep 3; kill -SIGINT $$; } &

echo "Waiting for sigint"
sleep 5
echo "Still running"
Run Code Online (Sandbox Code Playgroud)

输出是:

Waiting for sigint
caught
Still running
Run Code Online (Sandbox Code Playgroud)

如果你的观察是正确的,那么最后一行就不会存在.