Skip to content

Instantly share code, notes, and snippets.

@Shoozza
Created August 25, 2026 12:17
Show Gist options
  • Select an option

  • Save Shoozza/2e0b479478ff53cbccece1d2b46a5848 to your computer and use it in GitHub Desktop.

Select an option

Save Shoozza/2e0b479478ff53cbccece1d2b46a5848 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# ~/.local/bin/ssh-agent-start.sh
AGENT_ENV="$HOME/.ssh/agent.env"
agent_is_running() {
[ "$SSH_AGENT_PID" ] && kill -0 "$SSH_AGENT_PID" 2>/dev/null
}
agent_has_keys() {
ssh-add -l &>/dev/null
}
load_agent_env() {
[ -f "$AGENT_ENV" ] && source "$AGENT_ENV" >| /dev/null
}
add_keys() {
local keys=()
shopt -s nullglob
keys=(~/.ssh/*_rsa ~/.ssh/*_ecdsa ~/.ssh/*_ecdsa_sk ~/.ssh/*_ed25519 ~/.ssh/*_ed25519_sk ~/.ssh/*_dsa)
shopt -u nullglob
if [ ${#keys[@]} -gt 0 ]; then
ssh-add "${keys[@]}"
else
echo "No keys found in ~/.ssh/"
fi
}
start_agent() {
echo "Starting new ssh-agent..."
ssh-agent > "$AGENT_ENV"
chmod 600 "$AGENT_ENV"
source "$AGENT_ENV" >| /dev/null
add_keys
}
load_agent_env
if agent_is_running; then
if ! agent_has_keys; then
echo "Agent running but no keys loaded, adding keys..."
ssh-add
else
echo "Agent already running with keys loaded."
fi
else
start_agent
fi
#echo "SSH_AUTH_SOCK=$SSH_AUTH_SOCK"
#echo "SSH_AGENT_PID=$SSH_AGENT_PID"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment