Capture keyboard interrupt in bash
Asked Answered
W

1

5

I have a function in bash which captures the keyboard interrupt. The function looks like this:

user_interrupt(){
        echo -e "\n\nKeyboard Interrupt detected."
        sleep 2
        echo -e "\n Cleaning up..."
        rm -rf /usr/local/src/mysources
}

Now, in the same script, I have another function called install() that installs a few packages from source one after the other using the standard ./configure, make, make install process. The idea is to capture the user interrupt from while running the 3 installations one after the other. Question is, where do I place the following statements:

trap user_interrupt SIGINT
trap user_interrupt SIGTSTP

So should I place it as the first statement inside the install() function? Or do I need an if-else condition?

Whoop answered 20/9, 2013 at 9:25 Comment(0)
T
8

I guess that you want to exit after detecting user interrupt (of course after the clean up act in done). If that is so, you need to say exit after the rm -rf ... line in your function. Unless you do so, trap would catch a signal SIGINT for example, perform the tasks in your user_interrupt function and the script would continue to execute.

To answer the other question, simply define the function you've mentioned at the top of your script followed by the two trap commands and subsequently by your remaining code (the install() function and so on). trap would catch the mentioned signals and you do not need any explicit handling for that.

Tor answered 20/9, 2013 at 9:42 Comment(2)
did u mean at the beginning of the install() function?Whoop
No, outside the function; before it. I assume that you'd want to capture interrupts for all functions in the script.Tor

© 2022 - 2024 — McMap. All rights reserved.