What is the difference between ~. (tilde dot) and "exit" when exitting an SSH connection

Solution 1:

exit tells your current shell to quit. Since (when not having a tunneled connection, e.g. X11, active) that means that the process that sshd invoked on the server side exited, SSH then disconnects.

~. is the "magic" escape sequence that SSH captures and immediately disconnects (including the X11 tunnel).

So, no, these aren't interchangeable. If you want your remote shell (or whatever program is running remotely) to gracefully exit, you should end it accordingly.

Solution 2:

It is well described already in the other answer, but I would add some background:

Single SSH connection today can contain several sessions (your shells, command), TCP forwarding channels and X11 forwarding channels. And there comes the difference:

  • Writing exit (or Ctrl+D) tears down the session channel, but if there are active some X11 channels (for example gvim leaves several connections to X server handling clipboard and title, which is not closed by exit). Writing exit will leave this X11 application running and your terminal will "hang" until it is closed.

  • Writing ~. tears down the whole connection. You can notice if you run some X11 application, that it is also closed when you write ~..