Git Reset Branch to Master (main)

Published on Monday, 10 October 2022

How to Reset a Git Branch to Master (Main)

Resetting a branch to match the state of the master (or main, as it is now commonly called) branch is a common requirement, especially when you need to discard local changes or ensure that your branch starts fresh from a known good state. Below, I'll detail the Git commands necessary to perform this reset, explaining why and when you might need to use each command.

Why Reset to Master?

There are several reasons why you might need to reset a branch to the master:

  • Discarding Experimental Changes: If you have experimented on a branch and the changes are no longer needed, resetting to master allows you to start over with a clean slate.
  • Aligning with Updated Project Standards: If master has received updates that include critical fixes or project standards changes, you might need to reset your branch to incorporate these before continuing your work.
  • Resolving Merge Conflicts: Sometimes, it’s easier to reset your feature branch to master and reapply your changes incrementally than to resolve complex merge conflicts.

Commands to Reset Your Branch

To reset your branch to align with master, follow these steps:

git clean --force

Purpose: This command removes all untracked files from your working directory. It is particularly useful for cleaning up generated files and build artifacts that are not part of the repository. Use this command with caution, as it will permanently delete these files.

git switch master

Purpose: Previously git checkout master, this command switches your current branch to master. This step ensures you are on the master branch to sync it with the remote or pull the latest updates before you reset your feature branch.

git switch -C {branchName}

Purpose: This command switches back to your original branch (replace {branchName} with your branch's name) and resets it to the current state of master. The -C flag forces the creation of the branch from the master, effectively overwriting it with master's content.

Conclusion

By following these steps, you can ensure your branch is reset and synced with master, providing a clean, up-to-date starting point for your work. These commands are powerful tools in Git's arsenal, helping maintain clean and manageable project histories. Always make sure to backup important changes or work in a test branch if unsure about the results of these operations.