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.
SSH – Using LocalCommand on Exit
bashosxssh
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. Fromman bash
: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 you want to execute it on the local machine, create a function wrapper around
ssh
. Something like the following should work:That may be too simple for your needs, but you get the idea.