Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I'm trying to create a shell script that, among other things, starts up ssh-agent and adds a private key to the agent. Example:

#!/bin/bash
# ...
ssh-agent $SHELL
ssh-add /path/to/key
# ...

The problem with this is ssh-agent apparently kicks off another instance of $SHELL (in my case, bash) and from the script's perspective it's executed everything and ssh-add and anything below it is never run.

How can I run ssh-agent from my shell script and keep it moving on down the list of commands?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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.

share|improve this answer
    
Thanks! Creating a separate script and ending the script with exit did the trick. –  Dan Oct 23 '13 at 16:29
add comment

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).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.