I have a script that runs several rsync commands. When I do ctrl+c, only the running rsync command is stopped and then next one in the script starts.
How can I change the script so that ctrl+c will stop the whole process instead of just one command?
There is no logic in the script right now, just rsyncing of different folders one after the other.
For the sake of having an example, let's assume it's
#!/bin/bash
rsync -artv foo/ bar/
rsync -artv another/ folder/
Unfortunately, it's a little bit ugly. In order to ensure that bash gets the SIGINT when you hit ctrl-c, you can't let rsync run in the foreground. Instead, you need to do something like:
#!/bin/bash
trap 'kill $!; exit 1;' INT
rsync -artv foo/ bar/ &
wait
rsync -artv another/ folder/ &
wait
But that doesn't quite do exactly what you want because this sends SIGTERM instead of SIGINT to rsync. Unfortunately, because rsync is running asynchronously (ie, in the background), bash starts it with SIGINT ignored, so you can't rely on forwarding the SIGINT. (It is quite possible that rsync resets its signal handling to accept SIGINT, but in general with this technique, you should assume that the running job is ignoring SIGINT.)
The main issue is that if rsync is running in the foreground then bash doesn't see the SIGINT unless you happen to send it after one rsync has finished and before the next has started. By running the jobs in the background, bash will see the signals.
Note that this is not at all robust; that's one of the joys of dealing with signals in *nix.