From b1262b8f4e8199d067390617b3362dd44c667b6e Mon Sep 17 00:00:00 2001 From: Mike Crute Date: Sat, 24 Sep 2022 09:35:36 -0700 Subject: Prefer running ssh agent --- .bashrc | 55 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/.bashrc b/.bashrc index b66a75f..70ce621 100644 --- a/.bashrc +++ b/.bashrc @@ -633,31 +633,40 @@ function get_ssh_agent esac done - for path in "${TMPDIR:-/tmp}"/ssh-*/agent.*; do - basepath=$(basename $path) - sockpath=$(dirname $path) - - export SSH_AUTH_SOCK=${path} - export SSH_AGENT_PID=${basepath##agent.} - - # When no files are present matching the pattern the pattern itself is - # passed through. shopt -s nullglob would fix this but too much - # fiddling to make it work without polluting the parent shell state. - if [[ "$SSH_AGENT_PID" == "*" ]]; then - [[ -n "$debug" ]] && echo "No agents found" - break - fi + # Prefer to use the running agent if there's one already running. + # Otherwise try to figure out where a suitable agent is and connect. + # to it. + if ! _ssh_agent_is_running; then + [[ -n "$debug" ]] && echo "No agent running, commencing search..." + + for path in "${TMPDIR:-/tmp}"/ssh-*/agent.*; do + basepath=$(basename $path) + sockpath=$(dirname $path) + + export SSH_AUTH_SOCK=${path} + export SSH_AGENT_PID=${basepath##agent.} + + # When no files are present matching the pattern the pattern itself is + # passed through. shopt -s nullglob would fix this but too much + # fiddling to make it work without polluting the parent shell state. + if [[ "$SSH_AGENT_PID" == "*" ]]; then + [[ -n "$debug" ]] && echo "No agents found" + break + fi - [[ -n "$debug" ]] && echo -n "Trying ${SSH_AUTH_SOCK} for ${SSH_AGENT_PID}... " + [[ -n "$debug" ]] && echo -n "Trying ${SSH_AUTH_SOCK} for ${SSH_AGENT_PID}... " - if _ssh_agent_is_running; then - [[ -n "$debug" ]] && echo "Success" - break - else - [[ -n "$debug" ]] && echo "Failure... removing ${sockpath}" - rm -rf "$sockpath" - fi - done + if _ssh_agent_is_running; then + [[ -n "$debug" ]] && echo "Success" + break + else + [[ -n "$debug" ]] && echo "Failure... removing ${sockpath}" + rm -rf "$sockpath" + fi + done + else + [[ -n "$debug" ]] && echo "Using already running agent..." + fi # If the agent still isn't connected after sourcing our local agent # state file then it probably isn't running at all. Start a new -- cgit v1.2.3