gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:02:20 24 4
gpt4 key购买 nike

当 shell 脚本在执行过程中被中断时,我想触发类似“rm -rf/etc/XXX.pid”的命令。就像使用 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.

下面是测试运行记录(一个完整输入的行,一个在任何输入之前按 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!!

关于bash - shell脚本中断时如何触发命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14702148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com