Skip to content

How to force pull in Github?

  • by
  • 2 min read

If you’re learning to code, learning Git is an essential skill that’ll help you massively. It allows developers to share and collaboratively work on projects. It’s also a great version management tool, meaning you can develop multiple reiterations of a project and work on individual issues without touching the main codebase. 

In this article, we’re talking about how you can do a force pull in Github and overwrite any existing files in your local repository. 

Also read: GitHub vs Git vs GitLab vs Bitbucket


Performing a force pull in Github

To prevent accidental overwrites, Git will never overwrite existing files in a repository by default. This means there’s no option to force a Git pull by default, but you can use a series of commands to force Git to overwrite any files already in the repository. 

Before we begin, remember that all uncommitted local changes to tracked files will be lost, even if the changes are staged. 

Step 1: The first step is to update all origin/<branch> references to their latest versions.

git fetch --all

Step 2: Next, backup your current branch. In this example, we’re referring to the master branch, but feel free to change the command to your needs. 

git branch backup-master

Step 3: Finally, push the latest commit to your repository using the command below. 

git reset --hard origin/master

The git reset command resets the master branch to what we just fetched in the first step. The --hard flag ensures that all files in the working tree match the files in origin/master.


Maintaining current commits during reset

If you want, you can save your current commits in a different branch during a forced pull. Enter the following commands one at a time after making the necessary changes according to your repository. 

git checkout master
git branch new-branch-to-save-current-commits
git fetch --all
git reset --hard origin/master

Also read: How to create a Git repository? How to connect it to GitHub?

Yadullah Abidi

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: yadullahabidi@pm.me.

>