Skip to content

Instantly share code, notes, and snippets.

@dschnare
Last active March 10, 2026 11:14
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/id_ed25519
ssh-add ~/.ssh/signing_ed25519
}
# Load existing connection details if they exist
if [ -f "$AGENT_ENV_FILE" ]; then
source "$AGENT_ENV_FILE" > /dev/null
fi
# Check if we are connected to a live agent, otherwise start one
if ! ssh-add -l >/dev/null 2>&1; then
start_agent
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
# Kill the ssh-agent process
if [ -n "$SSH_AGENT_PID" ]; then
eval "$(ssh-agent -k)" > /dev/null 2>&1
fi
# Remove the environment file so a fresh one is created next time
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