I frequently execute programs that take a long time on several remote servers:

for NUM in {1..100}; do ssh host-{NUM}.mydomain.com /usr/bin/takesalongtime; done

Most of the time I let this run in background (i.e. in a terminal emulator while doing something else) and wait for it to finish. However, sometimes I need to break the loop and continue or re-run it later.

Is there a way to stop such a loop running in an interactive bash after the current iteration without killing the current ssh or takesalongtime program in the process?

I.e. I want to do something, so that the loop behaves like I inserted a break; between the ssh command and done, so that it breaks the loop after completing takesalongtime on the current remote host.

1 Answer 1


Find the pid of the shell and send it a sigint. This will not stop the ssh, but when it finishes the shell will handle the signal and end the loop.

$ for i in {1..100}; do ssh -n localhost 'sleep 9;date'; done

in other terminal

$ ps fax
10636 ?        S      0:00          |   \_ xterm
10638 pts/2    Ss     0:00          |       \_ bash
12164 pts/2    S+     0:00          |           \_ ssh -n localhost sleep 9;date
$ kill -int 10638

If you have backgrounded the command by adding & to the end you can use kill -hup on the backgrounded shell.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .