Bash:当有 CTRL-C 时如何中断此脚本?
我编写了一个小型 Bash 脚本来查找所有 Mercurial 变更集(从提示开始),其中包含参数中传递的字符串:
#!/bin/bash
CNT=$(hg tip | awk '{ print $2 }' | head -c 3)
while [ $CNT -gt 0 ]
do
echo rev $CNT
hg log -v -r$CNT | grep $1
let CNT=CNT-1
done
如果我通过按 ctrl-c 中断它,当前执行的命令通常是“hg log”并且正是该命令被中断,但我的脚本仍在继续。
然后我正在考虑检查“hg log”的返回状态,但是因为我正在将它输入到 grep 中,所以我不太确定如何去做......
当它出现时我应该如何退出这个脚本被中断? (顺便说一句,我不知道该脚本是否适合我想做的事情,但它完成了工作,无论如何我对“中断”问题感兴趣)
I wrote a tiny Bash script to find all the Mercurial changesets (starting from the tip) that contains the string passed in argument:
#!/bin/bash
CNT=$(hg tip | awk '{ print $2 }' | head -c 3)
while [ $CNT -gt 0 ]
do
echo rev $CNT
hg log -v -r$CNT | grep $1
let CNT=CNT-1
done
If I interrupt it by hitting ctrl-c, more often than not the command currently executed is "hg log" and it's that command that gets interrupted, but then my script continues.
I was then thinking of checking the return status of "hg log", but because I'm piping it into grep I'm not too sure as to how to go about it...
How should I go about exiting this script when it is interrupted? (btw I don't know if that script is good at all for what I want to do but it does the job and anyway I'm interested in the "interrupted" issue)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
放置在脚本的开头:
trap 'echo Interrupted; exit' INT
编辑:如下面的评论所述,由于管道的原因,可能不适用于OP的程序。
$PIPESTATUS
解决方案有效,但如果管道中的任何程序以错误状态退出,将脚本设置为退出可能会更简单:set -e -o pipelinefail
Place at the beginning of your script:
trap 'echo interrupted; exit' INT
Edit: As noted in comments below, probably doesn't work for the OP's program due to the pipe. The
$PIPESTATUS
solution works, but it might be simpler to set the script to exit if any program in the pipe exits with an error status:set -e -o pipefail
像这样重写你的脚本,使用 $PIPESTATUS 数组来检查失败:
Rewrite your script like this, using the $PIPESTATUS array to check for a failure:
$PIPESTATUS
变量将允许您检查管道中每个成员的结果。The
$PIPESTATUS
variable will allow you to check the results of every member of the pipe.