Skip to content

Instantly share code, notes, and snippets.

@andremueller
Created December 27, 2023 15:52
Show Gist options
  • Save andremueller/4fb80b36b2ed7090b596468dc97022d8 to your computer and use it in GitHub Desktop.
Save andremueller/4fb80b36b2ed7090b596468dc97022d8 to your computer and use it in GitHub Desktop.
Starting ssh-agent in bash
## start ssh-agent
# see https://stackoverflow.com/questions/40549332/how-to-check-if-ssh-agent-is-already-running-in-bash
USER="${USER:-$(id -un)}" # fix for Windows git-bash which does not set the USER variable
export SSH_AUTH_SOCK=${SSH_AUTH_SOCK:-/tmp/ssh-agent-${USER}.sock}
agent_run_state=$(ssh-add -l > /dev/null 2>&1 ; echo $?)
# agent_run_state == 0 agent runs with keys
# agent_run_state == 1 agent runs without keys
# agent_run_state == 2 agent is not running
if [[ $agent_run_state = 2 ]] ; then
# Load stored agent connection info.
[[ -r ~/.ssh-agent-${HOSTNAME} ]] && eval "$(<~/.ssh-agent-${HOSTNAME})" >/dev/null
rm -f "$SSH_AUTH_SOCK"
ssh-agent -a "$SSH_AUTH_SOCK" > ~/.ssh-agent-${HOSTNAME}
eval "$(<~/.ssh-agent-${HOSTNAME})" >/dev/null
echo "Running ssh-agent with PID ${SSH_AGENT_PID} on ${HOSTNAME}"
fi
if [[ $agent_run_state != 0 ]] ; then
# do this individually for all keys you need to be added
ssh-add $HOME/.ssh/id_ed25519_MYSERVER
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment