Bratish Goswami

Personal website and blog

Auto-starting SSH Agent on Login

Getting tired of typing my SSH passphrase every time I want to push code to GitHub. Been looking into ways to automatically start ssh-agent when I log in. Every time I start a new terminal session, I have to run:

ssh-add ~/.ssh/id_rsa

And then type my passphrase. This gets annoying when you're doing a lot of git pushes throughout the day.

The Solution

Found a good solution that automatically starts ssh-agent and loads your keys. Add this to your .bash_profile:

SSH_ENV="$HOME/.ssh/agent-environment"

function start_agent {
   echo "Initialising new SSH agent..."
   /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
   echo succeeded
   chmod 600 "$SSH_ENV"
   . "$SSH_ENV" > /dev/null
   /usr/bin/ssh-add;
}

# Source SSH settings, if applicable
if [ -f "$SSH_ENV" ]; then
   . "$SSH_ENV" > /dev/null
   ps -ef | grep $SSH_AGENT_PID | grep ssh-agent$ > /dev/null || {
       start_agent
   }
else
   start_agent
fi

How It Works

This script is pretty clever:

  1. First time: Creates a new ssh-agent and saves the environment variables
  2. Subsequent times: Checks if the agent is still running
  3. If agent died: Starts a new one
  4. If agent exists: Just sources the existing environment

The Benefits

  • Only asks for your passphrase once per session
  • Automatically handles agent restarts
  • Works across multiple terminal windows
  • No need to remember to run ssh-add

Testing It

After adding this to your .bash_profile, open a new terminal. You should see:

Initialising new SSH agent...
succeeded

Then it will prompt for your SSH key passphrase. After that, all git operations should work without asking for the passphrase again.