DIY & Music & Guitar & Beer & Tech

Gitbash under windows using single ssh-agent across terminals

Recently gitbash changed default sourcing to bash_profile instead of bashrc. Not big of a deal but if you, like me, share same ‘dot files’ for interactive and local login sessions (think desktop vs server) then this is a minor issue that needs to be addressed. Simplest fix is to change start of gitbash with ‘login’ flag i.e. ‘-l’ instead of (only) ‘-i’. This will source bashrc as well – problem solved.

Now, for using single ssh agent, i tested quite a few ways of doing this. Wind up with the following code. It starts out with determining if running on windows, then spawns one agent and adds my keys to it. It performs some cleanup on exiting (all) terminals. Note: I use ConEmu as a wrapper for gitbash.

if [[ $(uname -s) == Linux ]]
then
    echo Linux no auto ssh agent handling
else
    #echo $(uname -s)
	SSH_ENV=$HOME/.ssh/environment</code>
# start the ssh-agent
function start_agent {
    echo "Initializing new SSH agent..."
    # spawn ssh-agent
    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo succeeded
    chmod 600 "${SSH_ENV}"
    . "${SSH_ENV}" > /dev/null
    #/usr/bin/ssh-add
    ssh-add ~/.ssh/key_one
    ssh-add ~/.ssh/key_two
    ...
}
if [ -f "${SSH_ENV}" ]; then
    . ${SSH_ENV} > /dev/null
    ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
    start_agent;
}
else
    start_agent;
fi
function finish {
    # Your cleanup code here
    echo ---------------------------------
    rm -rf $HOME/.ssh/environment
}
trap finish EXIT
fi

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.