Skip to content

Instantly share code, notes, and snippets.

@no1xsyzy
Created June 10, 2020 08:00
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 no1xsyzy/951967d7929826876924fd6d70b26eef to your computer and use it in GitHub Desktop.
Save no1xsyzy/951967d7929826876924fd6d70b26eef to your computer and use it in GitHub Desktop.
Make ssh-agent idempotent
# Usage: . /path/to/auto-ssh-agent
# Check if exists ssh-agent in current session
if env | grep -q '^SSH'; then
echo Agent pid $SSH_AGENT_PID;
else
# Cached ssh-agent info is user-specified
_SOURCE_DIR="~/.local/run"
_SOURCE_FILE="${_SOURCE_DIR}/ssh-agent"
mkdir -p "$_SOURCE_DIR"
# if exists cached file
if [ -f "$_SOURCE_FILE" ]; then
# find the pid in it and find the program in it.
_SOURCE_FILE_PID=$( tail -1 "${_SOURCE_FILE}" | cut -d " " -f 4 | cut -d ";" -f 1 )
_PROCESS_PRG=$( ps -elf | awk '$4 == "'${_SOURCE_FILE_PID}'" {print $15}' )
# if the process is an ssh-agent
if [ "ssh-agent" = "$_PROCESS_PRG" ]; then
source "$_SOURCE_FILE"
else
# create new ssh-agent and cache it
eval $( ssh-agent -s | tee "$_SOURCE_FILE" )
fi
unset _SOURCE_FILE_PID
unset _PROCESS_PRG
else
# create new ssh-agent and cache it
eval $( ssh-agent -s | tee "$_SOURCE_FILE" )
fi
unset _SOURCE_DIR
unset _SOURCE_FILE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment