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 [email protected] 'cd /some/path; bash -l'), but that runs before disconnecting rather than after connecting.

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

1 Answer 1

17

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

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.