What's Actually Happening
You've finished your work on a remote server and type exit or logout to close the SSH connection. Instead of returning to your local shell, the terminal freezes. The cursor blinks but nothing happens, sometimes for minutes before the connection finally closes or you're forced to kill the terminal.
The Error You'll See
After typing exit:
user@remote:~$ exit
logout
[hanging... nothing happens]The session appears stuck. Pressing keys does nothing. Eventually you might see:
Connection to remote-server.com closed.But only after a long delay, sometimes 30 seconds to several minutes.
Why This Happens
SSH waits for all processes in the session to terminate before closing. When you have background jobs, hung processes, or active X11/agent forwarding connections, SSH patiently waits for them to clean up. The most common culprits are:
- Background processes started with
&that weren't properly disowned - X11 forwarding connections that didn't close cleanly
- SSH agent forwarding with stale connections
- Process substitution or redirected output still pending
Step 1: Check for Background Jobs
Before you exit, always check for running or stopped jobs:
jobs -lThis shows background jobs in your current shell:
[1]+ 12345 Running sleep 1000 &
[2]- 12346 Stopped vim file.txtIf you see stopped jobs (the Stopped status), they must be resolved before clean exit.
Step 2: Terminate or Disown Background Processes
For jobs you want to keep running after you disconnect, use nohup and disown:
nohup long-running-process &
disownFor jobs you want to stop, kill them:
kill %1Or forcefully:
kill -9 %1Step 3: Check for Stray Processes
Sometimes processes detach from the shell but SSH still tracks them. Find them:
ps -u $USERLook for any processes you started that might still be running. Kill them if needed:
pkill -u $USER process-nameStep 4: Quick Escape When Stuck
If your session is already hung, you have several options:
Option A: Use SSH escape sequences
Press Enter, then ~. (tilde followed by period):
[Enter]
~.This immediately terminates the SSH connection without waiting for cleanup.
Option B: Kill from another terminal From a different terminal on your local machine:
pkill -f "ssh.*remote-server"Step 5: Prevent Future Hangs
When starting long-running processes, use nohup and redirect output:
nohup ./script.sh > output.log 2>&1 &
disownOr use screen or tmux for persistent sessions:
tmux new -s work
./long-script.sh
# Press Ctrl+B, then D to detach
exitVerify the Fix
Your SSH sessions exit cleanly when:
- 1.
jobs -lreturns no output before you exit - 2.The connection closes within 1-2 seconds of typing
exit - 3.You can immediately start a new SSH session without issues
To test, start a fresh SSH session, do nothing, and exit. It should close instantly. If it doesn't, check your shell configuration files for processes that start automatically.