Skip to content

Instantly share code, notes, and snippets.

@aspen-roller
Last active May 28, 2021 23:28
Show Gist options
  • Save aspen-roller/3cec8924610dea874117c3e1ac93b0c7 to your computer and use it in GitHub Desktop.
Save aspen-roller/3cec8924610dea874117c3e1ac93b0c7 to your computer and use it in GitHub Desktop.
automatically start ssh-agent #ssh #util
# SSH key must already be created
SSH_ENV=$HOME/.ssh/environment
function start_agent {
echo "Initializing new SSH agent..."
/usr/bin/ssh-agent | sed 's/^echo/#echo/' >| "${SSH_ENV}"
echo succeeded
chmod 600 "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
# load all private ssh keys
find ~/.ssh/ -type f -not -path "**/.archive/*" -exec grep -l "PRIVATE" {} \; | xargs ssh-add &> /dev/null
}
if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || { start_agent; }
else
start_agent;
fi
# check for added keys
ssh-add -l
# add default key ~/.ssh/id_rsa
ssh-add
# add specific key
ssh-add ~/.ssh/github

Add the code from .profile to your own ~/.profile.

This is slightly different from the StackOverflow answer: Start ssh-agent on login. If noclobber has been set in your environment, then writing to .ssh/environment will fail. In this version, the file is overwritten with >|. See why 'cannot overwrite existing file'?.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment