How can I automatically run a command on the local terminal after exiting a ssh connection? Is there any hook or event that could be handled for this?


Leverage an alias or better a function.

For example:

ssh () { command ssh "$@"; echo foobar; }

Now, you can run:

ssh mysite

after you exit from the ssh session, echo foobar will be run.

Change echo foobar with the actual command you need to run, and of course you can tack multiple commands if you want.

To make the function definition permanent, put it in your ~/.bashrc.

Also note that, it might not always be desired to have the function named as ssh when you want to explicitly use the external ssh. In that case, you can use any one of the following to skip the ssh function to get external ssh binary:

command ssh mysite

or rename the function to something else e.g. sshfunc:

sshfunc () { ssh "$@"; echo foobar; }
  • 4
    note: I recommend renaming the function to something else than "ssh", so you keep ssh it's original meaning... maybe: ssh2 ? or sshcmd ? (otherwise you could forget its side effects when doing things like: ssh user@host 'cd /somewhere/ && tar cf - | gzip -c -' > local_backup_of_somewhere.tgz : this will be wrong as it will contain "foobar" at the end...) – Olivier Dulac Oct 10 '16 at 9:46
  • @OlivierDulac Good point, edited. – heemayl Oct 10 '16 at 10:15
  • \ssh 'ssh' and "ssh" only escapes an alias, command ssh will run the command (escaping both alias and function). – Olivier Dulac Oct 10 '16 at 10:23
  • @OlivierDulac Didn't know that, fixed. – heemayl Oct 10 '16 at 10:26
  • It is like that in bash, can maybe vary with other shells... but now, I like your answer with those additions, you get my +1 ^^ – Olivier Dulac Oct 10 '16 at 10:26

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.