krckumar
krckumar

Reputation: 544

Ctrl-C to stop the shell script execution

I have a shellscript as follows. This doesn't terminates on pressing Ctrl-C. Can you guide me on how to modify the following code to kill the execution on Ctrl-C as input.

#!/bin/bash

validateURL()
{
        regex='(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]'
        string=$1
        if [[ $string =~ $regex ]]
        then
                echo "0"
        else
                echo "1"
        fi
}

RED='\033[0;31m'

echo -n "Enter the URL :"
while read URL_REGISTRY
do
        if [ $(validateURL $URL_REGISTRY) == "0" ]
        then
                break
        else
                echo -e "${RED}Wrong URL entered."
                tput sgr0
                echo -n "Enter the URL again :"
        fi
done

Upvotes: 2

Views: 2124

Answers (2)

rghome
rghome

Reputation: 8831

Try:

stty intr "^C"

If that does not work, try:

stty -a

and figure out what is wrong with your settings. If you can't, update your answer with the output of stty -a.

Also make sure that you have not trapped the interrupt signal (2) as mentioned in the other answers.

Upvotes: 0

P.P
P.P

Reputation: 121397

The only way this can happen is if your shell blocks SIGINT. As per your description, your shell seems to do it. Reset the SIGINT in your shell so that your script receives SIGINT.

Run the following in your shell and run the script:

trap - SIGINT

Upvotes: 1

Related Questions