9

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.

1

2 Answers 2

11

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.

1
  • I needed the command to be executed on the local machine. Thanks for the suggestion. It works smoothly. Commented Jun 18, 2012 at 16:51
1

You are on the right track. If the ssh session is a login shell (instead of a remote command), bash will source /etc/bash.logout and ~/.bash_logout when you exit the shell.

If you want to execute a remote command, then you can force bash to be a login shell. The LocalCommand could be similar to this:

bash -l -c /execute/some/command

From man 1 bash

-c string   If  the  -c  option  is  present, then commands are read from 
string.  If there are arguments after the string, they are assigned to 
the positional parameters,  starting with $0.
-l   Make bash act as if it had been invoked as a login shell 

When  a login shell exits, bash reads and executes commands from the 
files ~/.bash_logout and /etc/bash.bash_logout, if the files exists.
1
  • 1
    Not if executing a remote command (If command is specified, it is executed on the remote host instead of a login shell.). However, reading the OP question closer, it appears he wants something to happen locally, so I think you answer is more appropriate.
    – George M
    Commented Jun 15, 2012 at 19:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .