Bash – Kill backgrounded SSH when shell exits

bashssh

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'

Best Answer

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
Related Question