如何在 shell 脚本中断时触发命令?

问题描述 投票:0回答:2

我想在 shell 脚本在执行过程中被中断时触发像“

rm -rf /etc/XXX.pid
”这样的命令。喜欢使用
CTRL+C
谁能帮我在这里做什么?

bash shell sh interrupt-handling
2个回答
24
投票

虽然这可能会让很多人感到震惊,但您可以使用

bash
内置
trap
来捕获信号 :-)

好吧,至少那些可以被困住,但是

CTRL-C
通常与
INT
信号相关(可以用
stty
来改变它,但为了简单起见,让我们忽略这种可能性)。

因此,您可以捕获信号并执行任意代码。例如,以下脚本将要求您输入一些文本,然后将其回显给您。如果你碰巧产生了一个

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 SIGINT trap to call function.

read -p "What? "         # Ask user for input,
echo "You said: $REPLY"  #   then echo back.

trap SIGINT              # Restore signal handling.

接下来是测试运行记录(完整输入的行、在任何输入之前按

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!!

3
投票

trap
用于捕获脚本中的信号,包括按下 Ctrl-C 时生成的
SIGINT

© www.soinside.com 2019 - 2024. All rights reserved.