Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

So right now I have a bash script that runs a command on a remote machine using ssh. The machine running the bash script is a Linux machine and the remote machine is a Windows machine running cygwin. The bash script contains the following lines

ssh -i key.pem user@ip "command1" &
# some other commands here, not included because they're not relevant to question

command1 is a long-running process. Currently when I Ctrl-C out of my bash script before wait completes, command1 is still running on the remote machine. It essentially becomes detached and uncontrollable. I want it to terminate when I Ctrl-C, otherwise the remote machine will be littered with many instances of command1 if I constantly terminate my script prematurely. Note the background & is necessary because I want to run other commands while that command is running.

I've tried several methods already

  1. Add the "-t -t" option for pseudo-terminal
  2. Added the below line in the hopes of passing SIGINT to my ssh sessions

    trap 'kill -INT -$$' SIGINT

    I also did a variation of the trap command where I got a list of child PIDs and iterated through it killing each one. That didn't work either. SIGHUP also did not work.

So far the only way I've gotten command1 to terminate is if I just run the ssh command

ssh -t -i key.pem user@ip "command1"

without backgrounding it and type Ctrl-C in the same terminal. It doesn't even work if I send a SIGINT or SIGHUP from another terminal.

What is the correct way to terminate remote commands via backgrounded ssh?

NOTE This only happens when the remote machine is a cygwin environment.

share|improve this question
Instead of waiting at the end of your script, why don't you just bring ssh back into the foreground after those other commands are complete? (ie fg) –  Zoredache Feb 19 '14 at 20:15
It's also possible that I terminate before I reach the wait. Some of the other commands do take time to do. Even if I replace the wait with a fg, there's a possibility that it won't get there. –  UrbenLegend Feb 19 '14 at 20:20

1 Answer 1

Try something like this:

function killcommand1() {
    ssh -i key.pem user@ip 'kill `cat/tmp/command1_pid`'

trap "killcommand1" SIGINT

ssh -i key.pem user@ip 'command1 & echo $! > /tmp/command1_pid' &
# other commands

This worked for me going from one Linux system to another, and unfortunately I don't have a cygwin installation available, but this way of sending the kill command could work anyway.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.