How To Force Git Pull To Overwrite Changes?
When working on a Git repository, a developer sometimes needs to overwrite local changes with remote changes. However, when using the git pull command, the developer can stumble on a similar error message to this:
txterror: Untracked working tree file 'file.txt' would be overwritten by merge.
Luckily, Git offers easy ways of doing a git pull force to overwrite local changes.
This article will explore multiple ways of overwriting local changes with the latest updates from the remote.
Let's get to it 😎.
When forcing git pull to overwrite local changes, you first need to decide if you want to save the changes or wish to remove them. Depending on this, the approach will be different.
How to force git pull (without saving local changes)?
To force git pull to overwrite local changes without saving them, you need to fetch all the updates from the remote and reset your current branch.
Here is the process to follow:
1. Fetch all the updates from the remote using the git fetch command. This command only downloads updates. It doesn't merge anything.
bashgit fetch --all
2. Reset your current branch to get the updates from the remote and remove your local changes.
bashgit reset --hard origin/your-branch
3. Remove untracked files and directories using the git clean command.
bashgit clean -f -d
4. Use the git pull command normally.
bashgit pull
That's it! You've successfully overwritten local changes with remote changes.
Note: If you want to be safe, back up your branch before overwriting local changes by creating a new branch using the git branch command.
How to force git pull (and save local changes)?
If you want to keep your local changes when fetching the latest changes from the remote, you need to save them in the stash before updating your branch.
Here is the process to follow:
1. Stash all your changes.
bashgit stash --include-untracked
2. Use the git pull command to fetch and merge the changes from the remote.
bashgit pull
That's it!
If you want to re-apply your stashed changes, use the git stash apply or git stash pop commands.
Final thoughts
As you can see, overwriting local changes with remote changes is easy, and you have different ways of archiving it in Git.
However, be extra cautious if you decide to remove your local changes.
You could lose your changes forever if you change your mind.
Here are other Git tutorials that I wrote for you to enjoy: