Bash: how to abort this script when there is CTRL-C?

I wrote a tiny Bash script to find all Mercurial changes (starting from the tooltip) containing the string passed in the 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 pressing ctrl-c, the "hg log" command is most often executed, and this command is interrupted, but my script continues.

Then I thought about checking the return status of "hg log", but because I pass it to grep, I'm not too sure how to do this ...

How do I exit this script when it is interrupted? (By the way, I don’t know if this script is good for what I want to do, but it does the job, and in any case I am interested in the “interrupted” problem)

+6
bash copy-paste interrupt
source share
3 answers

Rewrite the script as follows, using the $ PIPESTATUS array to verify the failure:

 #!/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 if [ 0 -ne ${PIPESTATUS[0]} ] ; then echo hg failed exit fi let CNT=CNT-1 done 
+5
source share

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

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

+6
source share

The $PIPESTATUS allows you to check the results of each channel member.

+1
source share

All Articles