// dot this script, don't just run it as a script (which would run it in its own sub-shell) because you need the variables to be set in the context of your current shell.


#!/bin/bash

for FILE in $(find /tmp/ssh-???*[0-9]* -type s -user ${LOGNAME} -name "agent.[0-9]*")
do

GOT_AGENT=0

SOCK_PID=${FILE##*.}

PID=$(ps -fu${LOGNAME}|awk '/ssh-agent/ && ( $2=='${SOCK_PID}' || $3=='${SOCK_PID}' || $2=='${SOCK_PID}' +1 ) {print $2}')

SOCK_FILE=${FILE}

SSH_AUTH_SOCK=${SOCK_FILE}; export SSH_AUTH_SOCK;
SSH_AGENT_PID=${PID}; export SSH_AGENT_PID;

ssh-add -l | grep : > /dev/null
if [ $? = 0 ]
then
GOT_AGENT=1
echo "Agent pid ${PID}"
break
fi
echo "Skipping pid ${PID}"

done

if [ $GOT_AGENT = 0 ]
then
ssh-add
fi


Before I used the find I was using this, but it's not as accurate, and the socket file is more important than the PID when you're trying to connect to an existing agent, so it makes sense to me to start with that.
(unless your find would be horribly slow for some reason)


for PID in $(ps -furoot | awk '/ssh-agent/{print $2}')
do
let SOCK_PID=PID-1
SOCK_FILE=$(ls -d /tmp/ssh-???*${SOCK_PID}/agent.${SOCK_PID})


Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/owXsi6M3NgE/10897