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.

  • Which shell do you use (on remote)?
    – ibuprofen
    Jun 27, 2021 at 3:49
  • @ibuprofen I use bash both locally and on remote Jun 27, 2021 at 3:52

1 Answer 1


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


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.