Ctrl+C to break an infinite loop and then do something outside the loop in a bash script without exiting?

0

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

Posted 2017-02-24T11:44:50.817

Reputation: 11

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 – 2017-02-24T12:17:02.053

@Nifle I have included an example, how can I make that specific example work ? – quanta – 2017-02-24T13:24:37.650

Answers

2

#!/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

Posted 2017-02-24T11:44:50.817

Reputation: 31 337

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 – 2017-02-28T22:21:48.013

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 – 2017-03-01T18:57:23.720