Useful when used in conjunction with BashLogout and ssh-add.
Placing the following code in to your ~/.bash_profile
or ~/.profile
will attempt to re-use your most recently launched ssh-agent
, and then list the resident identities.
If there is no ssh-agent
already running, it will start one, specifying a default identity timeout period of 1 hour. You may then add your publickey identity using the ssh-add
command.
if [[ -n "$SSH_AUTH_SOCK" && -e "$SSH_AUTH_SOCK" ]] ; then
# Use forwarded agent.
ssh-add -l
elif SSH_AGENT_PID="$(pgrep -n -u "$USER" ssh-agent)" ; then
# Reuse existing agent.
export SSH_AGENT_PID
export SSH_AUTH_SOCK="$(find /tmp/ -mindepth 2 -maxdepth 2 -type s -user "$USER" -name "agent.$(( SSH_AGENT_PID - 1 ))" 2>/dev/null)"
# List keys already loaded in to an existing ssh-agent.
ssh-add -l
elif [[ -z "${AUTOSTART_SSH_AGENT:+x}" ]] ; then
# Start new ssh-agent, with key lifetime set to expire after 12 hours.
eval $(ssh-agent -t 3600)
fi