How to unfreeze terminal when SSH connection dies?

I"m using Mac 10.9.5 with bash shell. Occasionally when I ssh into another machine and then the connection dies (e.g. the Internet goes down or I move to a new location), the terminal window with the open SSH session is frozen and the only way I seem to be able to move ahead is to close it and start a new session.

Is there some way to configure things such that if the SSH session's connection dies, I will be returned back to my normal bash shell, as it was before I executed my SSH command?


Solution 1:

You can suspend and then kill the ssh process that's hung up. To do this you have to issue the escape sequence, suspend the ssh process, and then use kill -9 to kill that process.

The default escape key for the ssh that ships with OS X the ~ character. You have to enter it immediately after a new line for ssh to respect it. And then the key sequence Control-z is used to suspend and background a task in bash.

So try this key sequence:

Return

~

Control-z

If it works you'll see something like:

myhost.local:~ |ruby-2.2.0|
> ssh someremotehost
Last login: Fri Mar  6 14:15:28 2015 from myhost

someremotehost:~ |ruby-2.2.0|
> ~^Z [suspend ssh]

[1]  + 48895 suspended  ssh myremotehost

This line of output:

[1]  + 48895 suspended  ssh myremotehost

tell you the process ID of the ssh process on your machine. It's 48895 in this example. That process is still running, it's just been suspended and backgrounded. You need to kill it.

You can do that with the kill command. You want to kill it with prejudice so use the -9 option when you call kill like so:

myhost.local:~ |ruby-2.2.0|
> kill -9 48895
[1]  + 48895 killed     ssh someremotehost

Just use the PID of your ssh process when you call that command in place of the 48895 PID I used above.

And you'll have your prompt back.

Alternatively, you can open a second Terminal window and use ps to find the ssh process in the process list and issue the kill -9 call against the PID. Though, that kind of defeats the process of getting your prompt back in the original Terminal window, doesn't it?