Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: how to interrupt this script when there's a CTRL-C?

I wrote a tiny Bash script to find all the Mercurial changesets (starting from the tip) that contains the string passed in argument:

#!/bin/bash

CNT=$(hg tip | awk '{ print $2 }' | head -c 3)
while [ $CNT -gt 0 ]
do
    echo rev $CNT
    hg log -v -r$CNT | grep $1       
    let CNT=CNT-1
done

If I interrupt it by hitting ctrl-c, more often than not the command currently executed is "hg log" and it's that command that gets interrupted, but then my script continues.

I was then thinking of checking the return status of "hg log", but because I'm piping it into grep I'm not too sure as to how to go about it...

How should I go about exiting this script when it is interrupted? (btw I don't know if that script is good at all for what I want to do but it does the job and anyway I'm interested in the "interrupted" issue)

like image 271
SyntaxT3rr0r Avatar asked Mar 31 '10 09:03

SyntaxT3rr0r


People also ask

How do you stop a Ctrl-C process in Linux?

Turned out the way Ctrl-c works is quite simple — it's just a shortcut key for sending the interrupt (terminate) signal SIGINT to the current process running in the foreground. Once the process gets that signal, it's terminating itself and returns the user to the shell prompt.

How does bash handle Ctrl-C?

Many signals are available in bash. The most common signal of bash is SIGINT (Signal Interrupt). When the user presses CTRL+C to interrupt any process from the terminal then this signal is sent to notify the system. Bash trap command.

How do I stop a bash script from running?

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.

How do you prevent Ctrl-C cause the termination of a running bash script?

How do I disable Control-C? You need to use the trap command which can enable or disable keyboard keys such as Crtl-C. SIGINT is Crtl-C and it is represented using number 2. Signal names are case insensitive and the SIG prefix is optional.


1 Answers

Place at the beginning of your script: trap 'echo interrupted; exit' INT

Edit: As noted in comments below, probably doesn't work for the OP's program due to the pipe. The $PIPESTATUS solution works, but it might be simpler to set the script to exit if any program in the pipe exits with an error status: set -e -o pipefail

like image 149
Arkku Avatar answered Sep 20 '22 14:09

Arkku