Is there a way to execute a command on the local machine after disconnecting from an ssh server?

This would have the same behavior as ssh_config LocalCommand that executes a command on the local machine after successfully connecting to the server.

This could be used to set terminal window title to that of the current server. Using LocalCommand when connecting, and that something else after disconnecting.

Alternatively, is there a way to automatically run a command after a specific command using bash?

  • 3
    Is this different from running ssh user@server; othercommand? – Kusalananda Nov 14 '18 at 12:08
  • That's the effect it should have, running another command after disconnection, but it has to be automatic. Using a shell alias would be an option. – Jean Vincent Nov 14 '18 at 16:10
  • Would you need it for non-interactive SSH connections too, like when using rsync or sftp? – Kusalananda Nov 14 '18 at 16:13
  • It probably does not need to work using non-interactive connections, so the alias solution might work when using ssh directly to connect to a server. But it would not work if the ssh connection was done via a script using /usr/bin/ssh – Jean Vincent Nov 14 '18 at 16:23

Not ssh specific, but as you mention bash, did you consider ~/.bash_logout? Mayhap extended by an ssh specific section?

  • ~/.bash_logout would run on the target server. It needs to run on the local server. I am experimenting right now with a bash function to sort-of alias ssh – Jean Vincent Nov 14 '18 at 16:52

There doesn't seem to be an ssh solution to this problem.

So I have implemented a bash function to alias ssh:

function ssh {
  set_title $1

  $(which ssh) $@

  set_title "$(whoami) @$(hostname)"

As my problem is mostly for interactive ssh sessions this works for me.

  • What's that double-setting of the title about? – LinuxSecurityFreak Nov 16 '18 at 11:53
  • The first one is to set the title to the name of the target server. The second one, after exiting from the server allows to reset the title to that of the local server. This way the title always corresponds to the current server. – Jean Vincent Nov 16 '18 at 19:07
  • 1
    You really should clarify this in your answer. It is useless without this information. Anyway, welcome to Unix & Linux. – LinuxSecurityFreak Nov 16 '18 at 19:32

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.