Skip to content

Instantly share code, notes, and snippets.

@basinilya
Created June 5, 2015 19:13
Show Gist options
  • Save basinilya/7a5aab8d56575a2f616b to your computer and use it in GitHub Desktop.
Save basinilya/7a5aab8d56575a2f616b to your computer and use it in GitHub Desktop.
Alternative to killing ssh-agent in ~/.bash_logout
# prevent leaked/orphaned ssh-agent processes
if [ -z "$SSH_AUTH_SOCK" ]; then
eval "`ssh-agent`" >/dev/null
ssh-add 2>/dev/null
# create pipe handle to share across all processes
coproc (
read s # to avoid race condition do not die until we disown/do stuff with $COPROC
# detach from tty
setsid sh -c "
trap '' HUP # although we are detached, parent bash may still HUP us
read s # wait pipe EOF
ssh-agent -k # kill agent
" <&0 & # create grandchild and die
) >/dev/null 2>&1
disown
export _SSH_AGENT_HANDLE=${COPROC[1]}
# clear FD_CLOEXEC for write side of the pipe and unblock the child
eval "exec ${COPROC[0]}>&-; exec ${COPROC[0]}>&1 1>&${COPROC[1]} ${COPROC[1]}>&-; exec ${COPROC[1]}>&1 1>&${COPROC[0]} ${COPROC[0]}>&-; echo >&${COPROC[1]}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment