4

I have the following trap defined in my (long) script:

#!/usr/bin/env bash

function continue_on_ctrl_c() {
        echo "** CTRL-C trapped **"
        continue # jump to the next iteration in the for loop
}
trap continue_on_ctrl_c INT

... rest of the script...
for i in several things here; do
  echo "doing: $i"
  find "$i" ..... | sometreatments # some of those take a long time: I wish to skip those using ctrl-C
done

When I press ctrl-C to "cancel" the current find and jump to the next one, it calls the trap (I see the message the function echoes at first), but then it exits the shell script instead of going to the next iteration of the for loop.

 # ./longscript.bash
 doing: several
 ** CTRL-C trapped **
 #               #<-- ie, it exited to the prompt, instead of continuing the for loop

Whereas on a small "proof of concept" script, it works and continues to the next iteration.

#!/usr/bin/env bash

function continue_on_ctrl_c() {
        echo "** CTRL-C trapped **"
        continue # jump to the next iteration in the for loop
}
trap continue_on_ctrl_c INT

for i in 1 2 3 ; do
   echo " doing: $i "
   sleep 100
done

# ./continue.bash
 doing: 1
** CTRL-C trapped **
 doing: 2
** CTRL-C trapped **
 doing: 3
** CTRL-C trapped **
#

What should I look for in the first script that prevents it to just continue to the next iteration of the for loop but exits instead (whereas there is still 3 elements to be trated in the for loop)?

Is it because when I press I am in a subshell ( find ... | treatement ) ? But then it seems the top level shell( the one launching the script) is the one receiving the ctrl-C as it displays the message ...

I am at a loss here...

closed as off-topic by Kusalananda, Jeff Schaller, user34720, Satō Katsura, don_crissti May 25 '17 at 21:05

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Kusalananda, Jeff Schaller, Community, Satō Katsura, don_crissti
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Is this behavior specific to sometreatments? What happens if you replace that by something trivial, like cat ? – user8153 May 18 '17 at 21:29
  • I'll try to narrow down the condition, or rather go "up" from the proof-of-concept one to one that has the same behavior... – Olivier Dulac May 19 '17 at 13:13
  • @user8153: oh my.... I had a variable to decide between continue & break, and it appears I didn't set it properly : it was doing break instead ... I feel so dumb. I'll delete this question as it is for a non-existent problem – Olivier Dulac May 22 '17 at 13:09

Browse other questions tagged or ask your own question.