Running ssh-agent from a shell script

ssh-agent is supposed to start a session and when it finishes the user session is over. So any command after ssh-agent would perhaps be executed after logoff.

What you want is a session-script that contains your sessions commands like this:

#!/bin/bash
ssh-add /path/to/key
bash -i # or other session starter

Then start ssh-agent session-script.


Put the following at the top of your script:

eval `ssh-agent`

Your script should look like this:

#!/bin/bash
eval `ssh-agent`
ssh-add /path/to/key
...
...

Explanation

The backticks around ssh-agent collect its output. eval collects that output, concatenates it into a single command, and then executes the command. Then you can use ssh-add to provide your key credentials.


I tend to do something like this in scripts that require an agent.

#!/bin/bash

# if we can't find an agent, start one, and restart the script.
if [ -z "$SSH_AUTH_SOCK" ] ; then
  exec ssh-agent bash -c "ssh-add ; $0"
  exit
fi

... and so on.

Basically the first thing the script does it check to see if an agent is running. If it isn't exec is used to start a new process in place of the script. The agent is started, keys are added, and finally, the script is called again (see the $0).


I found this works for me.

eval `ssh-agent` # create the process
ssh-add ~/.ssh/priv_key # add the key
git -C $repo_dir pull # this line is the reason for the ssh-agent
eval `ssh-agent -k` # kill the process

I create the ssh-agent process, add the key, do what I need to do, then kill it. No need to check if it's running later.