Bash:当有 CTRL-C 时如何中断此脚本?

发布于 2024-08-27 13:32:35 字数 467 浏览 4 评论 0原文

我编写了一个小型 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

樱花坊 2024-09-03 13:32:35

放置在脚本的开头: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

只等公子 2024-09-03 13:32:35

像这样重写你的脚本,使用 $PIPESTATUS 数组来检查失败:

#!/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
    if [ 0 -ne ${PIPESTATUS[0]} ] ; then
            echo hg failed
            exit
    fi     
    let CNT=CNT-1
done

Rewrite your script like this, using the $PIPESTATUS array to check for a failure:

#!/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
    if [ 0 -ne ${PIPESTATUS[0]} ] ; then
            echo hg failed
            exit
    fi     
    let CNT=CNT-1
done
⒈起吃苦の倖褔 2024-09-03 13:32:35

$PIPESTATUS 变量将允许您检查管道中每个成员的结果。

The $PIPESTATUS variable will allow you to check the results of every member of the pipe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文