Skip to content

Instantly share code, notes, and snippets.

@mschmitt
Last active August 29, 2015 14:03
Show Gist options
  • Save mschmitt/6feb49f62c2c4b205045 to your computer and use it in GitHub Desktop.
Save mschmitt/6feb49f62c2c4b205045 to your computer and use it in GitHub Desktop.
#!/bin/bash
# /usr/local/bin/ssh-agent-bootstrap
#
# To run ssh-agent as an application user in the background
#
# Sourced from the user's ~/.bash_profile:
# . /usr/local/bin/ssh-agent-bootstrap
#
# In application startup, add:
# export SSH_AUTH_SOCK=~/.ssh/agent.socket
#### Common environment
# Used to exchange information between shell and daemon
#
# Non-default socket for the SSH agent
SOCKET=~/.ssh/agent.socket
# File that will contain the autogenerated SSH environment
ENV=~/.ssh/agent.env
# Source the existing environment if it exists
test -s $ENV && . $ENV > /dev/null
# Initial ssh-add -l
# to check whether the agent is running.
ssh-add -l >/dev/null 2>&1
if [ $? -eq 2 ]
then
# Agent is not running. Start it.
rm $SOCKET
ssh-agent -a $SOCKET > $ENV.new && mv $ENV.new $ENV
# Source environment again to catch the new PID.
. $ENV > /dev/null
echo "*** Started SSH agent (pid $SSH_AGENT_PID)."
fi
# Second ssh-add -l (in case the agent was running already)
# to check whether we need to add an ID.
ssh-add -l >/dev/null 2>&1
if [ $? -eq 1 ]
then
# No IDs in agent
echo "*** SSH agent (pid $SSH_AGENT_PID) is running without loaded IDs."
ssh-add
fi
# List loaded IDs
echo "*** SSH agent (pid $SSH_AGENT_PID) knows the following IDs:"
ssh-add -l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment