I know that ssh-add is "front-end" of ssh-agent.

But ssh-agent on my computer is already running (I could find it in top). When I type ssh-add, it said "Could not open a connection to your authentication agent".

How ssh-add communicate with ssh-agent in details?

My situation is

#! /bin/sh

# hello.sh

eval $(ssh-agent -s)


bash ./hello.sh

when I type

ssh-add some-new-key

in terminal,

It output that error message


The output of ssh-agent -s is some environment variable assignments, something like SSH_AUTH_SOCK=blahblah; export SSH_AUTH_SOCK etc. When you run eval $(ssh-agent -s), the shell executes that as code, and those variables get set in that shell. The variables there contain the information ssh-add needs to contact the agent, and they get inherited down from the shell to the ssh-add process.

But here, you're running it from inside hello.sh. The shell running the script is an independent process, distinct from the upper interactive shell that started hello.sh, and the variables don't get inherited "upwards".

Instead, if you source the script, with source hello.sh, or . hello.sh, it runs in the same shell, and the variables get assigned properly.

Though, if you're running multiple shells (multiple terminal emulators, SSH sessions, screen/tmux windows, whatever), you really only need one ssh-agent. You'll have to save the variable assignments to a file somewhere, and load them from e.g. .bashrc. But I don't know what exactly you're doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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