To reset your local branch to exactly match the remote repository, follow these steps:
Step-by-Step Guide
- Fetch the latest changes from the remote:
git fetch origin
- This updates your local references to the remote repository without altering your working files.
- Checkout your target branch (if not already on it):
git checkout main # Replace "main" with your branch name (e.g., master, develop)
- Reset your local branch to match the remote:
git reset --hard origin/main # Use the remote branch name (e.g., origin/master)
--hard
discards all local changes and resets your branch to the remote’s state.
- Delete untracked files/directories (optional cleanup):
git clean -df
-d
: Remove untracked directories.-f
: Force deletion (required).- Use
git clean -n
first to preview what will be deleted.
Example Workflow
# Fetch the latest remote state
git fetch origin
# Switch to the branch you want to reset (e.g., main)
git checkout main
# Reset to match the remote branch
git reset --hard origin/main
# Optional: Remove untracked files (e.g., build artifacts, logs)
git clean -df
Key Notes:
- Irreversible Action: This permanently discards local changes and commits. Back up work with
git stash
if needed. - Remote Branch Name: Ensure you reference the correct branch (e.g.,
origin/main
,origin/master
). - Collaboration: Avoid this on shared branches if others rely on your local commits.
What This Does:
git reset --hard
: Moves the branch pointer to the remote commit and overwrites your working directory.git clean -df
: Removes untracked files (e.g., temporary files, build artifacts).
By following these steps, your local branch will mirror the remote repository.