Skip to content

Instantly share code, notes, and snippets.

@wyrmiyu
Last active January 18, 2022 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyrmiyu/21318f657e3afc74ddce0a05951505cd to your computer and use it in GitHub Desktop.
Save wyrmiyu/21318f657e3afc74ddce0a05951505cd to your computer and use it in GitHub Desktop.
# Filename: check_ssh_agent.sh
#
# Description: Check if ssh-agent environment exists for the session and
# create it if it does not.
#
# NOTE:
# Do not run this command directly, but import it in your .bashrc file with:
#
# source /path/to/check_ssh_agent.sh
#
# Otherwise SSH_AGENT_PID and SSH_AUTH_SOCK environment variables are not set.
#
last_ssh_agent_file="${HOME}/.last_ssh_agent"
if [[ ! $SSH_AUTH_SOCK || \
! $SSH_AGENT_PID || \
! -e $SSH_AUTH_SOCK || \
! -e /proc/$SSH_AGENT_PID ]]
then
if [[ -r $last_ssh_agent_file ]]
then
source "$last_ssh_agent_file" > /dev/null
fi
fi
if [[ $SSH_AUTH_SOCK && \
$SSH_AGENT_PID && \
-e $SSH_AUTH_SOCK && \
-e /proc/$SSH_AGENT_PID ]]
then
true
# echo "ssh-agent is present, details:"
# echo "SSH_AUTH_SOCK=${SSH_AUTH_SOCK}"
# echo "SSH_AGENT_PID=${SSH_AGENT_PID}"
else
unset SSH_AUTH_SOCK SSH_AGENT_PID
echo "Starting ssh-agent..."
ssh_agent=$(ssh-agent)
if [[ $? == 0 ]]
then
echo "$ssh_agent" > "$last_ssh_agent_file"
source "$last_ssh_agent_file" > /dev/null
# echo "ssh-agent started, details:"
# echo "SSH_AUTH_SOCK=${SSH_AUTH_SOCK}"
# echo "SSH_AGENT_PID=${SSH_AGENT_PID}"
else
echo "Error: could not start ssh-agent" 1>&2
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment