Jat*_*rya 5 bash shell sh interrupt-handling
rm -rf /etc/XXX.pid当shell脚本在执行过程中被中断时,我想发出像" " 这样的命令.喜欢使用CTRL+C
任何人都可以帮我在这做什么?
虽然它可能会让许多人感到震惊,但您可以使用bash内置trap陷阱信号:-)
好吧,至少那些可以被困住的,但CTRL-C通常与INT信号有关.您可以捕获信号并执行任意代码.
以下脚本将要求您输入一些文本,然后将其回显给您.如果偶然,你产生一个INT信号,它只会咆哮你并退出:
#!/bin/bash
exitfn () {
trap SIGINT # Restore signal handling for SIGINT
echo; echo 'Aarghh!!' # Growl at user,
exit # then exit script.
}
trap "exitfn" INT # Set up SIGINT trap to call function.
read -p "What? " # Ask user for input.
echo "You said: $REPLY"
trap SIGINT # Restore signal handling to previous before exit.
Run Code Online (Sandbox Code Playgroud)
测试运行记录如下(完全输入的行,在任何条目之前按下CTRL-C的行,以及在按CTRL-C之前具有部分条目的行):
pax> ./testprog.sh
What? hello there
You said: hello there
pax> ./testprog.sh
What? ^C
Aarghh!!
pax> ./qq.sh
What? incomplete line being entere... ^C
Aarghh!!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3956 次 |
| 最近记录: |