How to force “git pull” to overwrite local files?
When you run git pull, Git merges the changes from the remote repository into your local branch. If there are conflicts or local changes, it may fail or require manual resolution. If you want to force git pull to overwrite your local files, here’s how you can do it:
Steps to Force git pull to Overwrite Local Files
1. Discard Local Changes
To ensure the remote branch completely overwrites local changes, discard all local modifications.
git reset --hard HEAD
This command:
- Resets your local branch to its last committed state.
- Discards any uncommitted changes.
2. Force git pull
Fetch and reset your local branch to match the remote branch.
git fetch origin
git reset --hard origin/<branch-name>
This process:
- Fetches the latest changes from the remote repository.
- Resets your local branch to match the state of the remote branch, overwriting local files.
Alternative: Using git pull with --rebase
You can force git pull to overwrite your local files using the --rebase option. This approach works when you want to keep your local commits but still apply remote changes.
git pull --rebase --strategy-option=theirs
This command:
- Rebases your local changes on top of the remote branch.
- Resolves conflicts in favor of the remote branch.
Force Overwriting Without Keeping Local Changes
If you’re sure you want to discard all local changes and completely replace them with the remote branch:
git fetch origin
git reset --hard origin/<branch-name>
Example:
git fetch origin
git reset --hard origin/main
What If You Have Untracked Files?
Untracked files are not removed by reset. To ensure a clean state:
git clean -fd
This command:
- Removes untracked files and directories (
-fforces deletion, and-dincludes directories).
Full Example
- Discard local changes and untracked
git reset --hard HEAD git clean -fd - Overwrite local branch with
git fetch origin git reset --hard origin/<branch-name>
Important Notes
- Data Loss: These commands (
reset,clean,pull --rebase, etc.) may result in data loss. Ensure you don’t need any uncommitted changes before proceeding. - Backup Changes: If unsure, create a backup of your files or stash your changes
git stash
No images available.