Work around a bug in ssh-add, where it doesn't always return 2 on failure.

This commit is contained in:
Darren 'Tadgy' Austin 2019-07-02 01:10:40 +01:00
commit 8de9fe7f56

22
.bashrc
View file

@ -1,11 +1,13 @@
# Functions. # Functions.
_agent_prompt_command() { _agent_prompt_command() {
hash ssh-add >/dev/null 2>&1 && { hash ssh-add >/dev/null 2>&1 && {
local SOCK local OUTPUT SOCK
declare -g _SSH_PROMPT_ERROR_ISSUED declare -g _SSH_PROMPT_ERROR_ISSUED
# Check the ssh agent socket is still alive. # Check the ssh agent socket is still alive.
ssh-add -l >/dev/null 2>&1 # Need to work around an ssh-add bug here: ssh-add doesn't always return 2 on failure
if (($? >= 2)); then # to contact the agent, so also check if any errors were produced.
OUTPUT=$(ssh-add -l >/dev/null)
if ((${PIPESTATUS[0]} >= 2)) || [[ ! -z "$OUTPUT" ]]; then
# Auth socket has become unusable, search for a new one. # Auth socket has become unusable, search for a new one.
SOCK="$(_find_agent_sock)" SOCK="$(_find_agent_sock)"
if ((${PIPESTATUS[0]} == 0)); then if ((${PIPESTATUS[0]} == 0)); then
@ -30,23 +32,23 @@ _agent_prompt_command() {
else else
_SSH_PROMPT_ERROR_ISSUED=0 _SSH_PROMPT_ERROR_ISSUED=0
fi fi
unset SOCK # unset SOCK
} }
} }
_clean_agent_socks() { _clean_agent_socks() {
local I SSH_AUTH_SOCK local I OUTPUT SSH_AUTH_SOCK
# Go through the array of sockets and validate each one. # Go through the array of sockets and validate each one.
for ((I = 0; I < ${#SOCKS[@]}; I++)); do for ((I = 0; I < ${#SOCKS[@]}; I++)); do
SSH_AUTH_SOCK="${SOCKS[$I]}" ssh-add -l >/dev/null 2>&1 OUTPUT="$(SSH_AUTH_SOCK="${SOCKS[$I]}" ssh-add -l >/dev/null)"
(($? >= 2)) && { ((${PIPESTATUS[0]} >= 2)) || [[ ! -z "$OUTPUT" ]] && {
unset SOCKS[$I] unset SOCKS[$I]
} }
done done
} }
_find_agent_sock() { _find_agent_sock() {
local I IFS=$'\n' REPLY SOCKS=() SSH_AUTH_SOCK="$SSH_AUTH_SOCK" local I IFS=$'\n' OUTPUT REPLY SOCKS=() SSH_AUTH_SOCK="$SSH_AUTH_SOCK"
# Load the array of sockets, minus the one we know is unusable. # Load the array of sockets, minus the one we know is unusable.
if ((${BASH_VERSINFO[0]} >= 4)); then if ((${BASH_VERSINFO[0]} >= 4)); then
mapfile -t SOCKS < <(egrep -v "^$SSH_AUTH_SOCK\$" ~/.ssh/agents 2>/dev/null) mapfile -t SOCKS < <(egrep -v "^$SSH_AUTH_SOCK\$" ~/.ssh/agents 2>/dev/null)
@ -57,8 +59,8 @@ _find_agent_sock() {
fi fi
# Search backwards through the list to find an active socket. # Search backwards through the list to find an active socket.
for ((I = (${#SOCKS[@]} - 1); I >= 0; I--)); do for ((I = (${#SOCKS[@]} - 1); I >= 0; I--)); do
SSH_AUTH_SOCK="${SOCKS[$I]}" ssh-add -l >/dev/null 2>&1 OUTPUT="$(SSH_AUTH_SOCK="${SOCKS[$I]}" ssh-add -l >/dev/null)"
(($? <= 1)) && [[ ! -z "${SOCKS[$I]}" ]] && { { ((${PIPESTATUS[0]} <= 1)) && [[ -z "$OUTPUT" ]]; } && [[ ! -z "${SOCKS[$I]}" ]] && {
printf "%s" "${SOCKS[$I]}" printf "%s" "${SOCKS[$I]}"
return 0 return 0
} }