On both my mobile device and Raspberry Pi (coincidentally AArch and ARM CPUs respectively), ssh-agent is not loaded by default.

I first have to start the ssh-agent:

eval `ssh-agent -s`

I then proceed to add the key to the agent:

ssh-add /home/jimjamz/.ssh/myKey

I'm prompted for a password and enter it. The key is then added to the agent:

Enter passphrase for /home/jimjamz/.ssh/myKey: 
Identity added: /home/jimjamz/.ssh/myKey (/home/jimjamz/.ssh/myKey)

I can then connect to my remote server without having to specify my key once again.

For the sake of convenience, I want to add the above to a script that starts the agent and adds the key:

eval `ssh-agent -s`
ssh-add /home/jimjamz/.ssh/myKey

When I run the script, I can see the agent process has started and I'm prompted for my private key's password. I enter this correctly and the key is added to the agent.

However, when I try to ssh to my remote server, I see the following:

Permission denied (publickey).

The problem seems to be with calling ssh-add within my bash script. If I manually call ssh-add outside of the script then attempt to ssh to my remote server, I can connect.

Why is it not recognising that the key is already added if ssh-add is called within a bash script?

If I run the bash script on one of my other machines (where ssh-agent is already loaded by default), the key that is added within the script can be used successfully to ssh to a remote server. It just appears not to work on devices where ssh-agent is not automatically running by default.

  • evaling the output of ssh-agent sets the environment variable SSH_AUTH_SOCK to the location of the agent's communication socket. Shell scripts run as subprocesses, so setting it in the subprocess's environment has no effect on your shell's environment (and hence the ssh command you run from it). Try running the script with the source command (or .), which runs it in the current shell rather than a subprocess. Aug 24, 2019 at 3:30
  • Yes, of course, I forgot about source. I use source to also configure environment variables for terminal windows where the variables are only required. This is the answer. @GordonDavisson If you would like to convert your comment into an answer, I can mark it as answered.
    – jimjamz
    Aug 24, 2019 at 11:28


You must log in to answer this question.

Browse other questions tagged .