Safely Sync a Local Git Branch to Remote with fetch, reset and Recovery
Sometimes a local branch must exactly match its remote-tracking branch. This discards local tracked changes and commits that are not present on the remote, so inspect and preserve anything valuable first.
Inspect the target
Replace main with the intended branch. git fetch updates remote-tracking references but does not modify working files.
Preserve a recovery point
If local commits or edits might be useful, create a backup branch and optionally stash uncommitted work:
Then make the checked-out branch match the verified remote target:
| |
This overwrites tracked working-tree and index changes. Untracked files remain; review them with git status and remove only explicit paths if they are genuinely unwanted. Do not run a broad git clean without first previewing its exact targets.
Recovery
The backup branch retains the previous commit. A stash retains saved working-tree changes, and git reflog may locate recent commits even without a backup. These are safety nets, not a substitute for checking the repository and branch before a destructive reset.
For ordinary collaboration, prefer merging, rebasing, or resolving conflicts. A hard reset is appropriate only when discarding the local state is the actual goal.