Shell脚本中断时如何触发命令? [英] How to fire a command when a shell script is interrupted?

查看:110
本文介绍了Shell脚本中断时如何触发命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当shell脚本在执行过程中被中断时,我想触发一个类似" rm -rf/etc/XXX.pid "的命令.就像使用 CTRL + C 谁能帮我在这里做什么?

I want to fire a command like " rm -rf /etc/XXX.pid" when the shell script is interrupted in the middle of its execution. Like using CTRL+C Can anyone help me what to do here?

推荐答案

虽然可能会吓到很多人,但是您可以使用内置的 bash 陷阱 trap 捕获信号:-)

Although it may come as a shock to many, you can use the bash built-in trap to trap signals :-)

好吧,至少可以捕获到那些 ,但是CTRL-C通常绑定到 INT 信号.您可以捕获信号并执行任意代码.

Well, at least those that can be trapped, but CTRL-C is usually tied to the INT signal. You can trap the signals and execute arbitrary code.

以下脚本将要求您输入一些文本,然后将其回显给您.如果有可能,您会生成一个 INT 信号,它只会对您咆哮并退出:

The following script will ask you to enter some text then echo it back to you. If perchance, you generate an INT signal, it simply growls at you and exits:

#!/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.

随后是测试运行记录(完整输入的行,在任何输入之前按CTRL-C的行以及在按CTRL-C之前具有部分输入的行):

A test run transcript follows (a fully entered line, a line with pressing CTRL-C before any entry, and a line with partial entry before pressing 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!!

这篇关于Shell脚本中断时如何触发命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆