windowssshgit-bashssh-agent

Stopping SSH Agent when closing Git Bash on Windows


After being hesitant of using ssh-agent for quite a while now, I finally decided to use it. I am typically on Windows working with git-bash. I was glad to find a helpful question about Running SSH Agent when starting Git Bash on Windows.

However, I did not find a question answering the opposite problem. How do you automatically close the ssh-agent when closing the git-bash.

A blog post about best pratices with ssh-agent triggered this idea. However, the solution there doesn't seem to fit 100% to my environment. I am not too familiar with all the configuration possibilities of Linux systems. But I figured that for .logout and.bash_logout to work you need to (a) start the shell as a login shell and (b) need to leave the shell using exit or logout commands.

Luckily, (a) seems to be the standard for git-bash. With the solution of the blog post the ssh-agent is stopped when I exit,logout the git-bash. As a Windows guy, however, most of the time I close everything - including command prompts - by means of the UI (the X marks the spot). From that some questions arise:

  1. Can you adapt the .logout,.bash_logout solution to also consider closing the git-bash via UI?
  2. If not, what would be a solid alternative?
  3. In either way, when multiple git-bash windows are open, how would you prevent stopping the ssh-agent as soon as the first git-bash is closed? Ideally, ssh-agent should only be stopped after the last git-bash is closed.
  4. Is there a completely different, preferable way of managing ssh-agent in a Windows environment.

Solution

  • You can wire-up a trap in your bashrc. The 'x' triggers an event called "SIGHUP".

    logout () { eval $(ssh-agent -k); }
    trap logout SIGHUP
    

    You can probably run some more complex code to see if there are additional bash terminals open before you run the command in the case where you don't want to kill the agent if bash is still open.