Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Ctrl+C to stop whole script not just current command

Tags:

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?

like image 275
PHP Learner Avatar asked Aug 21 '15 16:08

PHP Learner


People also ask

How do I stop a script in C?

Show activity on this post. Just press Ctrl + Z . It will stop your script entirely.

How do I stop a running script?

If it's running in the foreground, Ctrl-C (Control C) should stop it. Read the documentation on the ps command and familiarize yourself with its options.

How do I stop a shell script from command?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

How do I stop a bash script?

One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.


1 Answers

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.

like image 58
bishop Avatar answered Nov 11 '22 05:11

bishop