Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Share a ssh-agent between WSL bash instances, but kill it when the last instance closes
# add to .bashrc
# Set up ssh-agent
SSH_ENV="$HOME/.ssh/environment"
function start_ssh_agent {
echo "Initializing new SSH agent..."
touch $SSH_ENV
chmod 600 "${SSH_ENV}"
/usr/bin/ssh-agent | sed 's/^echo/#echo/' >> "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
# the next line can be removed if you don't want to be prompted for a passphrase start
/usr/bin/ssh-add
}
function kill_ssh_agent {
bash_count=$(pgrep -c bash)
if [ $bash_count -gt 2 ]; then
# don't kill agent when there's still a bash shell running;
# because this function will be executed inside a bash shell,
# pgrep will find *2* bash processes when exiting the last real bash
true
else
# do kill agent since this is the last bash
eval $(ssh-agent -k)
rm "${SSH_ENV}"
fi
}
# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
kill -0 $SSH_AGENT_PID 2>/dev/null || {
start_ssh_agent
}
else
start_ssh_agent
fi
trap kill_ssh_agent EXIT

.bashrc for persistent shared ssh-agent in Windows Subsystem for Linux

The script above marked as .bashrc will start a ssh-agent the first time a bash shell is launched. It records the agent's environmental variables in a file at ~/.ssh/environment. Whenever a subsequent shell is launched, it will first attempt to read ~/.ssh/environment and use the same agent, if the environment file exists and the process is alive.

When shells are closed by exiting, kill_ssh_agent runs automatically. It detects whether more bash processes are open, and will only kill the agent and delete the file if the current process is the last real shell. If another bash shell is still open, the agent stays alive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment