1

I have read so many answers and they all just suggest to kill the script or send it to the background etc. What I want is

while true do

something...

if(ctrl+c is pressed break)

done echo "Out of the loop"

I am outside the loop because ctrl+c was pressed and so I can do other stuffs here without exiting the script....

And this question is not a duplicate because I have searched for hours and no answer gives me what I want. That "Out of the loop" never gets printed, I tried so many examples from various answers !

Info: I use (1) Scientific Linux SL release 5.4 (Boron), (2) Ubuntu 16.04

Edit: I want this exact code to work

#!/bin/bash

loopN=0

while true
do

echo "Loop Number = $i"
i=$(($i+1))

#I want to break this loop when Ctrl+C is pressed

done

#Ctrl+C has been pressed so I am outside the loop going to do something..

echo "Exited the loop, there were $i number of loopsexecuted !"
#here I will execute some commands.. let's say date
date

#and then I will exit the script
quanta
  • 131
  • 7
  • You want to **trap** ''Ctrl-C'' Here are some examples http://stackoverflow.com/questions/12771909/bash-using-trap-ctrlc If you want more specific help show us what you tried (actual code) – Nifle Feb 24 '17 at 12:17
  • @Nifle I have included an example, how can I make that specific example work ? – quanta Feb 24 '17 at 13:24

1 Answers1

3
#!/bin/bash

#function called by trap
do_this_on_ctrl_c(){
    echo "Exited the loop, there were $i number of loops executed !"
    date
    exit 0
}

trap 'do_this_on_ctrl_c' SIGINT

loopN=0

while true
do
    echo "Loop Number = $i"
    i=$(($i+1))
done
Nifle
  • 34,203
  • 26
  • 108
  • 137
  • This is exactly what I wanted, thanks a lot. I have noticed that this works when I execute it using `./script.sh` but it fails if I `source script.sh` it. I am really new to this scripting business but I would very much like to learn. – quanta Feb 28 '17 at 22:21
  • strange problem again ! It works on Scientific Linux (SL release 5.4 boron) but on Ubuntu 16.04, `Ctrl + C` takes me out of the script before even calling the function `do_this_on_ctrl_c()` at all. What should I do to make it work on my Ubuntu ? – quanta Mar 01 '17 at 18:57