-
-
Save pacohope/09a0ce08545e1fd74d06ef80d37ff79f to your computer and use it in GitHub Desktop.
Reuse existing ssh-agent or start a new one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reuse an existing ssh-agent on login, or create a new one. Append this to your .bashrc | |
# This version also handles the case where the agent exists but has no keys. | |
function agent() { | |
GOT_AGENT=0 | |
DEFTEMP="/tmp" | |
for FILE in $(find "${TMPDIR:-$DEFTEMP}/ssh-"* -type s -user ${LOGNAME} -name "agent.[0-9]*" 2>/dev/null) | |
do | |
SOCK_PID=${FILE##*.} | |
typeset -i PID | |
PID=${SOCK_PID}+1 | |
ps "${PID}" 2>/dev/null | grep -q "ssh-agent" | |
if [ "$?" = "0" ] | |
then | |
SOCK_FILE=${FILE} | |
export SSH_AUTH_SOCK=${SOCK_FILE} | |
export SSH_AGENT_PID=${PID} | |
ssh-add -l > /dev/null | |
if [ $? != 2 ] | |
then | |
GOT_AGENT=1 | |
echo "Reused agent pid ${PID}" | |
break | |
else | |
unset SSH_AGENT_PID SSH_AUTH_SOCK | |
fi | |
else | |
echo "Skipping pid ${PID}" | |
fi | |
done | |
if [ $GOT_AGENT = 0 ] | |
then | |
eval `ssh-agent` | |
fi | |
} | |
agent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment