Source

homebin / ssh-session

Full commit
#!/bin/bash

# ssh-agent is great, saves me tons of time every day. But tmux does something
# strange (either it behaves like a login shell or I don't know what) that
# causes a new agent to be created for *every single tmux shell* which
# rather defeats the point. This script captures an agent's information and
# stores it in a file. Whenever it is invoked it will check the 
# source the file. If no file is present, it will start a new agent
# then source the file.

# Where to store our ssh-agent session info.

#set -x

SSH_AGENT_SESSION_FILE="$HOME/.ssh_session"

RUNNING_AGENT_PIDS=$(ps -u$USER | grep ssh-agent | cut -d' ' -f2)

if [ `echo $RUNNING_AGENT_PIDS | wc -w` -gt 1 ]; then
	echo "Too many ssh-agents, wiping them all!"
	for pid in $RUNNING_AGENT_PIDS; do
		echo `kill $pid`
	done

	if [ -e $SSH_AGENT_SESSION_FILE ]; then
		rm $SSH_AGENT_SESSION_FILE
	fi
fi


if [ -e $SSH_AGENT_SESSION_FILE ]; then
	echo "Found a session file"
	source $SSH_AGENT_SESSION_FILE
	if [[ $SSH_AGENT_PID == $RUNNING_AGENT_PIDS ]]; then
		echo "Matches running agent. Win!"
		exit 0
	else
		echo "Session file is stale, killing ssh agent."
		kill $RUNNING_AGENT_PIDS

		echo "Restarting with new agent"
		ssh-agent > $SSH_AGENT_SESSION_FILE
	fi
else
	echo "Running ssh-agent"
	ssh-agent > $SSH_AGENT_SESSION_FILE
fi