Skip to content

Instantly share code, notes, and snippets.

@dschnare
Last active April 27, 2026 15:39
Show Gist options
  • Select an option

  • Save dschnare/5da490f087d49bc339185fccae367f2c to your computer and use it in GitHub Desktop.

Select an option

Save dschnare/5da490f087d49bc339185fccae367f2c to your computer and use it in GitHub Desktop.
SSH agent mangement for .bashrc or .zshrc
# ==========================================
# SSH Agent Configuration
# ==========================================
# Only run this for interactive shells
if [[ $- == *i* ]]; then
AGENT_ENV_FILE="${HOME}/.ssh/agent-env"
start_agent() {
echo "Starting new ssh-agent..."
ssh-agent -s | sed 's/^echo/#echo/' > "$AGENT_ENV_FILE"
chmod 600 "$AGENT_ENV_FILE"
source "$AGENT_ENV_FILE" > /dev/null
ssh-add ~/.ssh/git_ed25519
ssh-add ~/.ssh/signing_ed25519
}
# 1. Check if we already have a working agent (e.g. inherited from parent shell).
# This avoids re-prompting inside subshells like `devbox shell`.
if ! ssh-add -l >/dev/null 2>&1; then
# 2. No inherited agent — try loading saved connection details.
if [ -f "$AGENT_ENV_FILE" ]; then
source "$AGENT_ENV_FILE" > /dev/null
fi
# 3. Still no working agent — start a fresh one.
if ! ssh-add -l >/dev/null 2>&1; then
start_agent
fi
fi
# --- Cleanup function for when the shell exits ---
cleanup_agent() {
# Count how many pseudo-terminals (tabs/windows) are currently open for your user.
# Linux uses 'pts/', macOS uses 'ttys'
local active_terminals=$(ps -u "$USER" -o tty= | grep -E -c "^(pts/|ttys)")
# If this is the last terminal closing (count is 1 or somehow less)
if [ "$active_terminals" -le 1 ]; then
if [ -n "$SSH_AGENT_PID" ]; then
eval "$(ssh-agent -k)" > /dev/null 2>&1
fi
rm -f "$AGENT_ENV_FILE"
fi
}
# Tell the shell to run the cleanup function right before it exits
trap cleanup_agent EXIT
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment