Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 12 down vote accepted

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; }
share|improve this answer
    
Great solution! Thank you... – Meysam 2 days ago
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 2 days ago
    
@OlivierDulac Good point, edited. – heemayl 2 days ago
    
\ssh 'ssh' and "ssh" only escapes an alias, command ssh will run the command (escaping both alias and function). – Olivier Dulac 2 days ago
    
@OlivierDulac Didn't know that, fixed. – heemayl 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.