How to fire a command when a shell script is interrupted?

二次信任 提交于 2021-01-27 04:06:32

问题


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?


回答1:


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

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.

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.

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



回答2:


trap is used to catch signals in scripts, including the SIGINT generated when Ctrl-C is pressed.



来源:https://stackoverflow.com/questions/14702148/how-to-fire-a-command-when-a-shell-script-is-interrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!