Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

git pull updates your current local working branch, and all of the remote tracking branches. It’s a good idea to run git pull regularly on the branches you are working on locally.
Without git pull , (or the effect of it,) your local branch wouldn’t have any of the updates that are present on the remote.
What Does git pull Do?
git pull is one of the 4 remote operations within Git. Without running git pull , your local repository will never be updated with changes from the remote. git pull should be used every day you interact with a repository with a remote, at the minimum. That’s why git pull is one of the most used Git commands.
git pull and git fetch
git pull , a combination of git fetch + git merge , updates some parts of your local repository with changes from the remote repository. To understand what is and isn’t affected by git pull , you need to first understand the concept of remote tracking branches. When you clone a repository, you clone one working branch, main , and all of the remote tracking branches. git fetch updates the remote tracking branches. git merge will update your current branch with any new commits on the remote tracking branch.
git pull is the most common way to update your repository.
However, you may want to use git fetch instead. One reason to do this may be that you expect conflicts. Conflicts can occur in this way if you have new local commits, and new commits on the remote. Just like a merge conflict that would happen between two different branches, these two different lines of history could contain changes to the same parts of the same file. If you first operate git fetch , the merge won’t be initiated, and you won’t be prompted to solve the conflict. This gives you the flexibility to resolve the conflict later without the need of network connectivity.
Another reason you may want to run git fetch is to update to all remote tracking branches before losing network connectivity. If you run git fetch , and then later try to run git pull without any network connectivity, the git fetch portion of the git pull operation will fail.
If you do use git fetch instead of git pull , make sure you remember to git merge . Merging the remote tracking branch into your own branch ensures you will be working with any updates or changes.
How to Use git pull
Common usages and options for git pull
- git pull : Update your local working branch with commits from the remote, and update all remote tracking branches.
- git pull —rebase : Update your local working branch with commits from the remote, but rewrite history so any local commits occur after all new commits coming from the remote, avoiding a merge commit.
- git pull —force : This option allows you to force a fetch of a specific remote tracking branch when using the <refspec> option that would otherwise not be fetched due to conflicts. To force Git to overwrite your current branch to match the remote tracking branch, read below about using git reset .
- git pull —all : Fetch all remotes — this is handy if you are working on a fork or in another use case with multiple remotes.
You can see all of the many options with git pull in git-scm’s documentation.
Examples of git pull
Working on a Branch
If you’re already working on a branch, it is a good idea to run git pull before starting work and introducing new commits. Even if you take a small break from development, there’s a chance that one of your collaborators has made changes to your branch. This change could even come from updating your branch with new changes from main .
It is always a good idea to run git status — especially before git pull . Changes that are not committed can be overwritten during a git pull . Or, they can block the git merge portion of the git pull from executing. If you have files that are changed, but not committed, and the changes on the remote also change those same parts of the same file, Git must make a choice. Since they are not committed changes, there is no possibility for a merge conflict. Git will either overwrite the changes in your working or staging directories, or the merge will not complete, and you will not be able to include any of the updates from the remote.
If this happens, use git status to identify what changes are causing the problem. Either delete or commit those changes, then git pull or git merge again.
Keep main up to date
Keeping the main branch up to date is generally a good idea.
For example, let’s say you have cloned a repository. After you clone, someone merges a branch into main. Then, you’d like to create a new branch to do some work. If you create your branch off of main before operating git pull , your branch will not have the most recent changes. You could accidentally introduce a conflict, or duplicate changes. By running git pull before you create a brach, you can be sure that you will be working with the most recent information.
Undo A git pull
To effectively «undo» a git pull , you cannot undo the git fetch — but you can undo the git merge that changed your local working branch.
To do this, you will need to git reset to the commit you made before you merged. You can find this commit by searching the git reflog . The reflog is a log of every place that HEAD has pointed — every place that you have ever been checked out to. This reflog is only kept for 30 to 90 days, depending on the commit, and is only stored locally. (The reflog is a great reason not to delete a repository if you think you’ve made a mistake!)
Run git reflog and search for the commit that you would like to return to. Then, run git reset —hard <SHA> to reset HEAD and your current branch to the SHA of the commit from before the merge.
Force git pull to Overwrite Local Files
If you have made commits locally that you regret, you may want your local branch to match the remote branch without saving any of your work. This can be done using git reset . First, make sure you have the most recent copy of that remote tracking branch by fetching.
git fetch <remote> <branch>
ex: git fetch origin main
Then, use git reset —hard to move the HEAD pointer and the current branch pointer to the most recent commit as it exists on that remote tracking branch.
git reset —hard <remote>/<branch>
ex: git reset —hard origin/main
_Note: You can find the remotes with git remote -v , and see all available remote tracking branches with git branch —all .
git pull with Rebase
If there have been new commits on both your local branch and the remote branch, a merge commit will be created when you git pull . This recursive merge is the default merge style when there are two splits in history being brought together. But, you may want history on a branch to be only one line.
You can update your local working branch with commits from the remote, but rewrite history so any local commits occur after all new commits coming from the remote, avoiding a merge commit.
This is done with git pull —rebase .
Using git pull —rebase does not affect the integrity of the changes or the commits, but it does affect how history looks in the commit parent/child relationship.
- git clone [url] : Clone (download) a repository that already exists on GitHub, including all of the files, branches, and commits.
- git status : Always a good idea, this command shows you what branch you’re on, what files are in the working or staging directory, and any other important information.
- git branch : This shows the existing branches in your local repository. You can also use git branch [banch-name] to create a branch from your current location, or git branch —all to see all branches, both the local ones on your machine, and the remote tracking branches stored from the last git pull or git fetch from the remote.
- git push : Uploads all local branch commits to the remote.
- git log : Browse and inspect the evolution of project files.
- git remote -v : Show the associated remote repositories and their stored name, like origin .
Get started with git and GitHub
Review code, manage projects, and build software alongside 40 million developers.
A3.5 Приложение C: Команды Git — Совместная работа и обновление проектов
Не так уж много команд в Git требуют сетевого подключения для своей работы, практически все команды оперируют с локальной копией проекта. Когда вы готовы поделиться своими наработками, всего несколько команд помогут вам работать с удалёнными репозиториями.
git fetch
Команда git fetch связывается с удалённым репозиторием и забирает из него все изменения, которых у вас пока нет и сохраняет их локально.
Мы познакомились с ней в разделе Получение изменений из удалённого репозитория — Fetch и Pull главы 2 и продолжили знакомство в разделе Удалённые ветки главы 3.
Мы использовали эту команду в нескольких примерах из раздела Участие в проекте.
Мы использовали её для скачивания запросов на слияние (pull request) из других репозиториев в разделе Ссылки на запрос слияния главы 6, также мы рассмотрели использование git fetch для работы с упакованными репозиториями в разделе Создание пакетов главы 7.
Мы рассмотрели тонкую настройку git fetch в главе и Спецификации ссылок.
git pull
Команда git pull работает как комбинация команд git fetch и git merge , т. е. Git вначале забирает изменения из указанного удалённого репозитория, а затем пытается слить их с текущей веткой.
Мы познакомились с ней в разделе Получение изменений из удалённого репозитория — Fetch и Pull главы 2 и показали как узнать, какие изменения будут приняты в случае применения в разделе Просмотр удалённого репозитория главы 2.
Мы также увидели как она может оказаться полезной для разрешения сложностей при перемещении веток в разделе Меняя базу, меняй основание главы 3.
Мы показали как можно использовать только URL удалённого репозитория без сохранения его в списке удалённых репозиториев в разделе Извлечение удалённых веток главы 5.
И наконец мы показали как проверять криптографические подписи полученных коммитов, используя опцию —verify-signatures в разделе Подпись коммитов главы 7.
git push
Команда git push используется для установления связи с удалённым репозиторием, вычисления локальных изменений отсутствующих в нём, и собственно их передачи в вышеупомянутый репозиторий. Этой команде нужно право на запись в репозиторий, поэтому она использует аутентификацию.
Мы познакомились с этой командой в разделе Отправка изменений в удалённый репозиторий (Push) главы 2. Там мы рассмотрели основы обновления веток в удалённом репозитории. В разделе Отправка изменений главы 3 мы подробнее познакомились с этой командой, а в разделе Отслеживание веток главы 3 мы узнали как настроить отслеживание веток для автоматической передачи на удалённый репозиторий. В разделе Удаление веток на удалённом сервере главы 3 мы использовали флаг —delete для удаления веток на сервере, используя git push .
На протяжении раздела Участие в проекте мы показали несколько примеров использования git push для совместной работы в нескольких удалённых репозиториях одновременно.
В разделе Публикация изменений подмодуля главы 7 мы использовали опцию —recurse-submodules чтобы удостовериться, что все подмодули будут опубликованы перед отправкой проекта на сервер, что может быть реально полезным при работе с репозиториями, содержащими подмодули.
В разделе Прочие хуки на стороне клиента главы 8 мы поговорили о триггере pre-push , который может быть выполнен перед отправкой данных, чтобы проверить возможность этой отправки.
Наконец, в разделе Спецификации ссылок для отправки данных на сервер главы 10 мы рассмотрели передачу данных с полным указанием передаваемых ссылок, вместо использования распространённых сокращений. Это может быть полезным если вы хотите очень точно указать, какими изменениями хотите поделиться.
git remote
Команда git remote служит для управления списком удалённых репозиториев. Она позволяет сохранять длинные URL репозиториев в виде понятных коротких строк, например «origin», так что вам не придётся забивать голову всякой ерундой и набирать её каждый раз для связи с сервером. Вы можете использовать несколько удалённых репозиториев для работы и git remote поможет добавлять, изменять и удалять их.
Эта команда детально рассмотрена в разделе Работа с удалёнными репозиториями главы 2, включая вывод списка удалённых репозиториев, добавление новых, удаление или переименование существующих.
Она используется практически в каждой главе, но всегда в одном и том же виде: git remote add <имя> <URL> .
git archive
Команда git archive используется для упаковки в архив указанных коммитов или всего репозитория.
Мы использовали git archive для создания тарбола ( tar.gz файла) всего проекта для передачи по сети в разделе Подготовка релиза главы 5.
git submodule
Команда git submodule используется для управления вложенными репозиториями. Например, это могут быть библиотеки или другие, используемые не только в этом проекте ресурсы. У команды submodule есть несколько под-команд — add , update , sync и др. — для управления такими репозиториями.
Updating a local repository with changes from a GitHub repository
I’ve got a project checked locally from GitHub, and that remote repository has since had changes made to it. What’s the correct command to update my local copy with the latest changes?
![]()
10 Answers 10
was: git pull origin master
now: git pull origin main
![]()
This should work for every default repo:
If your default branch is different than master , you will need to specify the branch name:
![]()
However you’ll need to merge any changes into your local branches. If you’re on a branch that’s tracking a remote branch on Github, then
will first do a fetch, and then merge in the tracked branch
This question is very general and there are a couple of assumptions I’ll make to simplify it a bit. We’ll assume that you want to update your master branch.
If you haven’t made any changes locally, you can use git pull to bring down any new commits and add them to your master .
If you have made changes, and you want to avoid adding a new merge commit, use git pull —rebase .
git pull —rebase will work even if you haven’t made changes and is probably your best call.
How to update a local forked repository from the original repository
![]()
Reading this article means you have a basic understanding of git and github and have contributed to a project which is open-sourced for contribution by raising a PR (pull request) to the original repository which will get reviewed by the owner(s) of the repository.
If everything went fine with the changes you made either in the documentation, fixes you made on issues or code(s) you refactored did not break the project, then chances are that your PR (pull request) will be accepted and get merged. This is a wholesome goal!
Perhaps your contributions are not accepted by the owner(s) of the repository, then chances are that a comment will be given as to why it’s not accepted.
Your PR (pull request) got accepted and is being merged into the master branch of the original repository? Abso-coded-lute-ly Sweet! .
Oh, wait! The changes you made could not be found on your forked repository? Argh!
Typically, this could conflict when you try to raise a PR (pull request) on another change you worked, and this is mainly because your forked repository is not up to date with the original repository.
So let’s see how we can update the forked repository with steps outlined below:
NB: I will be using an open-source project I contributed to
- Go to the original repository you forked from on GitHub and copy the URL path by clicking on the button icon outlined on the image in red.
2. Open your terminal on your PC (either git bash or the integrated terminal on your editor) and change directory to where the repository you cloned locally is. Make sure you are on the master branch of the local repository. If you are not already, key in git checkout master and press enter . This is because we are updating the master branch (locally) from the master branch (remote).
3. Key in git remote add upstream [paste the path you copied] and press enter , which in this case on the terminal it will look like git remote add upstream https://github.com/ipinfo/node.git
4. Still on the terminal, key in git remote -v just to be sure it was added.
6. key in another command that will update the local repository with every change that has been merged to the master branch of the original repository (remote) git pull upstream master and press enter
Then after doing all the steps outlined above your local repository (master branch) should now be up to date with the original repository master branch (remote). So now, you can push to update your master branch of the forked repository on GitHub too with git push origin master and press enter
And voila! That’s it! Your repository is now up to date with the original repository.
NB: For every change, you want to work on which you will raise a PR, always update your local repository first because new changes might have been added to the repository.
You need to update your local master branch by doing the step outlined in step 6. After which, you can then checkout to create a new branch you want to work on, by keying in git checkout -b [branch-name-here] on the terminal.
Kindly give a clap and share if this article helped you. Also, I’d very much love to reply to your comments too…. Thanks.