Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to spawn an SSH from my bash profile script that runs in the background for connection sharing (via its control socket). The problem I'm running into is a reliable way to ensure the SSH doesn't stay running once the TTY is closed (or more directly; once the parent bash shell has exited).

I know the shell can run commands (to terminate SSH) when it exits gracefully, but I'm trying to handle all possible scenarios where the shell doesn't get a chance to shut things down.

Is there a clever way I can do this?

The best idea I've had is

ssh -o PermitLocalCommand=yes -o LocalCommand='cat >/dev/null; kill $PPID' $HOST &

But this won't work because I need the command to only background once it has successfully started. Alternatively, I can't use -fN instead of the shell's & because the SSH -f only backgrounds after the LocalCommand has completed.

Also I'm trying to avoid running any command on the remote host. Otherwise I could probably do something like ssh -fN $HOST 'cat >/dev/null'

share|improve this question

If your shell is a login shell you can stop SSH master connection from ~/.bash_logout file:

ssh -O exit hostname

If the shell isn't a login shell you can set a trap in your ~/.bashrc file just after spawning SSH:

ssh -fN hostname
trap 'ssh -O exit hostname' EXIT
share|improve this answer
This works if the shell exits gracefully, I'm trying to cover a scenario where the shell doesnt exit gracefully. – Patrick Mar 12 '12 at 21:37
up vote 3 down vote accepted

I hate it when I answer my own question.

The solution I came up with is to use ControlPersist=3600 when starting the master ssh process. This way if the shell doesnt exit gracefully and kill ssh, then it'll shut itself down after an hour of inactivity. Though I still use a trap on exit to shut ssh down cleanly.

ssh -o ControlMaster=yes -o ControlPersist=3600 -o ControlPath=/tmp/ssh-%u-%h-%p-%r -Nf $HOST
trap "ssh -o ControlPath=/tmp/ssh-%u-%h-%p-%r $HOST -O exit" exit
share|improve this answer
Cool recipe. Thanks for answering your own question. – 0xC0000022L Jun 1 '14 at 1:26

Keep SSH Sessions running after disconnection

I don't know if this is what you are looking for but it helped me keep my program running after exiting the ssh shell.

share|improve this answer
No, not at all what I'm trying to do. – Patrick Mar 12 '12 at 16:18
I dont think that it will work. – pmaipmui Jun 23 '15 at 2:55

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.