How to force “git pull” to overwrite local files?

To force git pull and completely overwrite local files (discarding all local changes and untracked files), follow these steps. This is a destructive operation—ensure you don’t need your local changes before proceeding.

Step-by-Step Guide

1. Fetch the Latest Remote Changes

Update your local references to the remote repository’s state:

git fetch --all

2. Reset Your Local Branch to Match the Remote

Discard all local changes and reset your branch to the remote version:

git reset --hard origin/<branch-name>   # Replace `<branch-name>` (e.g., `main`, `master`, `dev`)

3. Delete Untracked Files/Directories

Remove any files/folders not tracked by Git (optional but recommended for a clean slate):

git clean -df
  • -d: Remove untracked directories.
  • -f: Force deletion (required).

Examples

Example 1: Overwrite the main Branch

git fetch origin
git reset --hard origin/main    # Reset to remote's main branch
git clean -df                   # Delete untracked files

Example 2: Overwrite a Feature Branch

git fetch origin
git reset --hard origin/feature/login   # Reset to remote's feature/login branch
git clean -df

Example 3: Overwrite master (Legacy Default Branch)

git fetch origin
git reset --hard origin/master
git clean -df

What These Commands Do

CommandEffect
git fetch --allFetches the latest changes from all remotes (no changes to files).
git reset --hard origin/XResets your branch to match the remote branch X and deletes all local changes.
git clean -dfDeletes untracked files/directories (e.g., build artifacts, logs).

When to Use This

  • You want to discard all local work and match the remote exactly.
  • You’re stuck in a merge conflict and want to start fresh.
  • The remote branch has changes that must override your local state (e.g., hotfixes).

Alternatives

1. Discard Local Changes Without Pulling

If you only want to undo local modifications (not fetch remote updates):

git checkout -- .       # Discard changes in tracked files
git clean -df           # Delete untracked files

2. Pull with Overwrite (Not Recommended)

Force a pull (combines fetch + reset):

git pull --force origin <branch-name>

Key Notes

  • Backup First: Use git stash to save work you might need later.
  • Branch Names: Replace <branch-name> with your branch (e.g., main, dev).
  • Remote Name: If your remote isn’t named origin, use its name (e.g., upstream).

Troubleshooting

  • Permission Denied: Close editors/IDEs using the files.
  • Wrong Branch: Double-check the branch name with git branch -a.
  • Recovery: Use git reflog if you accidentally reset the wrong commit.

By following these steps, you can force your local repository to mirror the remote, ensuring a clean, conflict-free state.

Leave a Reply

Your email address will not be published. Required fields are marked *