45

I have a script such as follows:

for ((i=0; i < $srccount; i++)); do
    echo -e "\"${src[$i]}\" will be synchronized to \"${dest[$i]}\""
    echo -e $'Press any key to continue or Ctrl+C to exit...\n' 
    read -rs -n1
    rsync ${opt1} ${opt2} ${opt3} ${src[$i]} ${dest[$i]}
done

If I press Ctrl+C in response to read command, the whole script will stop, but if press Ctrl+C while rsync command is running, just current rsync command will stop and the script will continue the for loop.

Is there any way to tell the script if the user pressed Ctrl+C while rsync is running, stop rsync and exit from the script itself?

2
  • opt1, opt2, opt3, srccount, src and destare defined in the previous line of the script. Commented Aug 21, 2015 at 16:56
  • 7
    trap "exit" INT. See unix.stackexchange.com/a/48432/50240 Commented Aug 21, 2015 at 16:56

2 Answers 2

62

Ctrl+C sends the interrupt signal, SIGINT. You need to tell bash to exit when it receives this signal, via the trap built-in:

trap "exit" INT
for ((i=0; i < $srccount; i++)); do
    echo -e "\"${src[$i]}\" will be synchronized to \"${dest[$i]}\""
    echo -e $'Press any key to continue or Ctrl+C to exit...\n' 
    read -rs -n1
    rsync ${opt1} ${opt2} ${opt3} ${src[$i]} ${dest[$i]}
done

You can do more than just exiting upon receiving a signal. Commonly, signal handlers remove temporary files. Refer to the bash documentation for more details.

Sign up to request clarification or add additional context in comments.

5 Comments

Be aware that this will not work if script is launched using "source": . script.sh
I recommend trap "echo; exit" INT to make sure your next shell prompt is on a clean line
trap "echo; exit" INT not returning to command input mode
@AravindVemula perhaps bash is still waiting for the command to finish? In the documentation linked in my answer note this: "When Bash receives a signal for which a trap has been set while waiting for a command to complete, the trap will not be executed until the command completes." If that is not it, feel free to post a new question.
@bishop your solution worked like a charm man, I was talking about one in the comment cheers 🎉
-15

Just press Ctrl + Z. It will stop your script entirely.

2 Comments

No, ctrl + z will only suspend the process. It will still be there and can be resumed by typing fg.
Not working as you say.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.