I am using git pull (without sudo) every day on my machine, I have one key in ssh folder (cat ~/.ssh/id_rsa.pub)

Problem is, that I cant call sudo git pull, because I am getting an error:

sudo git pull
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

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

Probably there is problem with my key.

I need to call it in my external script (using sudo).

How can I call sudo git pull ? How can I add key for sudo?

In short: pull doesnt work with sudo why?

  • 5
    Why are you using sudo to run git?
    – Kenster
    Commented Apr 3, 2020 at 13:35
  • 1
    There is something wrong with your workflow if you are required to use sudo with git.
    – Kusalananda
    Commented Apr 3, 2020 at 16:19
  • The author already stated why needs sudo: "I need to call it in my external script (using sudo).". Imagine that a script that requires to run with sudo needs to perform a git operation amongst it's tasks. I think that's the use case for the question. Commented Jan 19, 2022 at 17:28

2 Answers 2


When you run something with sudo without specifying a particular user, you are running it as root user.

As it seems you cloned your repository via SSH, git (actually SSH I guess) is looking for the SSH private key for the root user instead of the one of your user: /root/.ssh/ vs. /home/your-user/.ssh/.

You can try the following:

  • Run your script using sudo -E: The -E preserves your user environment variables to be defined when running on sudo (some SSH variables, I think SSH_AUTH_SOCK and/or SSH_AGENT_LAUNCHER will be required, but I don't know much about the details).

  • Inside your script, run the git command "as the user" instead "as root". To achieve that, you can rely on sudo again :)

    sudo -E -u $(logname) git pull

Notice that you're using sudo -E twice: One to call the script, and another to call git inside the script.

That should work :)

P.S. In case you need a finer grained control of which environment variables are exported to sudo, use --preserve-env=list option instead of -E.


When you use git with sudo it looks for a the key in /root/.ssh/ and not in /home/yourusername/.ssh/. You just have to copy it into the former and it should work.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .