Skip to content

Instantly share code, notes, and snippets.

@davidalpert
Created December 8, 2021 14:56
Show Gist options
  • Save davidalpert/45f4b63f305626eecf8d71af3a6c57d2 to your computer and use it in GitHub Desktop.
Save davidalpert/45f4b63f305626eecf8d71af3a6c57d2 to your computer and use it in GitHub Desktop.
.sh_ssh_agent.sh
# Note: ~/.ssh/environment should not be used, as it
# already has a different pururpose in SSH
env=~/.ssh/agent.env
# Note: Don't bother checking SSH_AGENT_PID. It's not used
# by SSH itself, and it might even be incorrect
# (for example, when using agent-forwarding over SSH).
agent_is_running() {
if [ "$SSH_AUTH_SOCK" ]; then
# ssh-add returns:
# 0 = agent running, has keys
# 1 = agent running, no keys
# 2 = agent not running
ssh-add -l >/dev/null 2>&1 || [ $? -eq 1 ]
else
false
fi
}
agent_load_env() {
. "$env" >/dev/null
}
agent_start() {
(umask 077; ssh-agent >"$env")
. "$env" >/dev/null
}
agent_has_keys() {
ssh-add -l >/dev/null 2>&1
}
agent_has_key() {
if [ "$1" ]; then
echo "looking for: $1"
ssh-add -l | grep "$1" >/dev/null 2>&1
else
false
fi
}
if ! agent_is_running; then
agent_load_env
agent_start
fi
if ! agent_has_keys; then
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_2
ssh-add ~/.ssh/id_rsa_3
clear
fi
unset env
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment