7

I'm remotely connecting to a shared server and I would like to have a line of code executed automatically in the remote machine before I close the connection (e.g. by pressing Ctrl+D).

More specifically, I'd like to kill the SSH agent before I leave, as I noticed it keeps running even after I'm gone. The agent is started by another program, so I thought it'd be easier to just kill it before I leave rather than changing how it is started.

Is it possible to automatically run an arbitrary command -- like the one below -- before closing an SSH connection?

# user attempts to close connection

an arbitrary code or script runs

eval "$(ssh-agent -k)"

connection is closed

Perhaps something similar to the -t flag (ssh -t user@domain.com 'cd /some/path; bash -l'), but that runs before disconnecting rather than after connecting.

1 Answers1

16

You can set a trap in .bashrc that runs when shell exits:

Something like

trap 'test -n "$SSH_AGENT_PID" && eval "$(/usr/bin/ssh-agent -k)"' 0

Optionally add a routine in .bash_logout

ibuprofen
  • 2,890
  • Great, I wasn't even aware of .bash_logout. Any of these two options work for me, thanks! – TheMechanic Jun 27 '21 at 04:25
  • 5
    @TheMechanic Yes. It is neatly "hidden" under "Bash Startup Files" https://www.gnu.org/software/bash/manual/bash.html#Bash-Startup-Files – ibuprofen Jun 27 '21 at 04:28