Bash Login Script To Auto Add Your SSH Agent/Key

~/.bashrc

FOLDIR=~/.tmp/sshagent
mkdir -p $FOLDIR/shell > /dev/null 2>&1
. $FOLDIR/shell/cmds.$(hostname -s) > /dev/null 2>&1
sshcheck=$(ssh-add -l 2>&1 | grep -i '^[0-9][0-9][0-9][0-9 ]')
if [ "$sshcheck" == "" ]
then
	mkdir -p $FOLDIR/sock > /dev/null 2>&1
	rm -frv $FOLDIR/sock/agent.$(hostname -s) > /dev/null 2>&1
	killall -9 ssh-agent > /dev/null 2>&1
	ssh-agent -a $FOLDIR/sock/agent.$(hostname -s) > $FOLDIR/shell/cmds.$(hostname -s)
	. $FOLDIR/shell/cmds.$(hostname -s) > /dev/null 2>&1
	ssh-add
fi

Description of the script above (nfs friendly):
* Attempt to run the last ssh-agent export commands and check for valid keys with the ssh-add command
* If nothing exists then kill any current ssh-agent processes and save a new set of ssh-agent export commands
* Run the current set of ssh-agent export commands and add the default ssh key with ssh-add

Leave a comment