How to Overwrite Local Changes in Git

John Wachira Feb 02, 2024
  1. Use the git pull Command to Overwrite Local Changes in Git
  2. Drop the Uncommitted Local Changes Using Git
  3. Keep the Uncommitted Local Changes Using Git
How to Overwrite Local Changes in Git

This article will discuss how you can overwrite your local changes with the git pull command in Git.

Use the git pull Command to Overwrite Local Changes in Git

The git pull command fetches and merges files from your remote to your local repository. We first need to understand how the git pull command works to overwrite files.

The git pull command is a combination of two commands:

  1. the git fetch command
  2. the git merge origin/Branch command

When we run the git pull command, Git fetches changes from the repository you cloned from, origin, and merges them with the current branch in your local repository.

Git will only run the git pull command successfully when you do not have uncommitted changes. If your index has some uncommitted changes, you will likely encounter errors.

Drop the Uncommitted Local Changes Using Git

If you do not need the uncommitted changes in your index, use the git reset command in the context below.

git fetch
git reset --hard HEAD
git merge origin/$CURRENT_BRANCH

The git reset --hard HEAD will discard the uncommitted changes to allow the git merge command to run.

Git has a shortcut for those who do not want to specify the branch to fetch from, using the @{u} argument in your command line.

git fetch
git reset --hard HEAD
git merge '@{u}'

Keep the Uncommitted Local Changes Using Git

For those who do not want to get rid of their uncommitted changes, you can either commit or stash them. Stashing your commits puts them away from your index, and you can restore them later.

The changes are still on Git but not visible. Run the git stash command before pulling from your repository.

You can utilize the git stash pop command to bring back your stashed changes. Note that the git stash pop command will apply your changes, removing the stash from your list.

git fetch
git stash
git merge '@{u}'
git stash pop

If the methods above do not work, we always have the git pull --force command.

You need to specify the source and recipient branch with this command. It is very similar to git fetch --force.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Pull