SSH – Using LocalCommand on Exit

bashosxssh

In ~/.ssh/config you can use the LocalCommand directive to execute a local command whenever you connect to a remote machine via SSH. But how do I execute a command when I exit an SSH connection? It seems that *.bashrc/.bash_profile* files are not sourced when connection ends or is closed.

Best Answer

It's not specified in the question if you want this executed on the local or remote machine. It's also not specified which shell is present on either machine, so I'm assuming bash for both.

If you want to execute it on the remote machine, look at ~/.bash_logout, which is executed when a login shell logs out gracefully. From man bash:

When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.

You can do a test in ~/.bash_logout to check if the shell being logged out of is an SSH session, something like the following should work:

if [[ $SSH_CLIENT || $SSH_CONNECTION || $SSH_TTY ]]; then
    # commands go here
fi

If you want to execute it on the local machine, create a function wrapper around ssh. Something like the following should work:

ssh() {
    if command ssh "$@"; then
        # commands go here
    fi
}

That may be too simple for your needs, but you get the idea.

Related Question