Skip to content

Instantly share code, notes, and snippets.

@tomquisel
Created February 7, 2015 00:00
Show Gist options
  • Save tomquisel/303fc37d0e854d59b672 to your computer and use it in GitHub Desktop.
Save tomquisel/303fc37d0e854d59b672 to your computer and use it in GitHub Desktop.
find ssh agent socket
function findagent {
if ssh-add -l; then
echo "Your SSH Agent is already working."
return 0
fi
for sock in `ls /tmp/ssh-*/agent.*`; do
export SSH_AUTH_SOCK=$sock
if ssh-add -l; then
echo "Your SSH Agent is fixed. New socket=$sock."
return 0
fi
done
echo "Could not find any working SSH Agent sockets."
return 1
}
@kadarmarton
Copy link

I like this approach, very functional. I added some more checks to my own version:

function setup_ssh_agent {
	if
		echo "List of running SSH agents:"
		pgrep --list-full --uid $USER --exact ssh-agent
	then
		local oldnullglob="$(shopt -p nullglob)"
		shopt -s nullglob
		local -a try_socks=($SSH_AUTH_SOCK /tmp/ssh-*/agent.*)
		$oldnullglob

		local txt
		for sock in "${try_socks[@]}"
		do
			echo -n "Trying $sock ... "
			export SSH_AUTH_SOCK=$sock
			if
				txt=$(ssh-add -l) ||
				[[ "$txt" == "The agent has no identities." ]]
			then
				echo "OK"
				return
			else
				echo
			fi
		done

		echo "A working SSH Agent socket could not be found"
		return 1
	else
		echo -n "None found. Starting one... "
		. <(ssh-agent)
	fi
}

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