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'


3 Answers 3


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
  • This works if the shell exits gracefully, I'm trying to cover a scenario where the shell doesnt exit gracefully.
    – phemmer
    Mar 12, 2012 at 21:37

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
  • Cool recipe. Thanks for answering your own question. Jun 1, 2014 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.

  • 2
    No, not at all what I'm trying to do.
    – phemmer
    Mar 12, 2012 at 16:18
  • I dont think that it will work.
    – Nainita
    Jun 23, 2015 at 2:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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