Search code examples
bashsshssh-agent

Why can't I `source` ssh-agent and ssh-add with in bash script?


When I tried git push, I get the following error.

ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I know that I should specify my own key here, so I type the following in bash window, and it works fine.

ssh-agent bash
ssh-add ~/.ssh/id_rsa_lrz
git push

However, I'd like make things easy, so I have a set_env.sh like this

ssh-agent bash
ssh-add ~/.ssh/id_rsa_lrz

And I type in my bash window like this

. set_env.sh
git push

However, I get the ERROR: Repository not found. error again, but why?


Solution

  • This is because when you run :

    . set_env.sh
    

    You will be inside the bash session setup by ssh-agent bash where ssh-add ~/.ssh/id_rsa_lrz has not run yet.

    What you need is putting in set_env.sh

    eval "$(/usr/bin/ssh-agent)"
    ssh-add ~/.ssh/id_rsa_lrz