Git
Version Control
HEAD
master
main

Difference between HEAD and master or main

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In the world of Git, many terms and concepts can be confusing for both newcomers and seasoned developers. Among these are "HEAD" and "master" (or "main"). Understanding the distinction between these terms is crucial for effective version control practices. This article aims to demystify these terms by providing a detailed comparison, technical explanations, and practical examples.

Understanding Git References

Before delving into the differences, it's essential to grasp what each term represents in the context of Git version control.

Definition: `HEAD` is a symbolic reference to the current branch's most recent commit.

  • Role: In Git, `HEAD` always points to the tip of the current branch. It tells Git where you are in the commit history. When you switch branches using, for example, `git checkout`, you are moving the `HEAD` from one branch to another.
  • Usage: `HEAD` is often used in commands to refer to the latest commit, such as `git reset --hard HEAD` to reset the working directory to the last commit.
    Example:
  • Role: The `master` or `main` branch usually represents the code that is in production or the stable version of your software. It is the common base from which other branches—feature branches, hotfixes, etc.—emerge.
  • Usage: The favored branch name `main` harmonizes better with inclusive language initiatives. This branch often acts as the focal point for merging the most stable and tested changes.
    • When you execute `git checkout ``<another-branch>```, the `HEAD` is moved to a new location. It now points to the tip of the ```<another-branch>``` instead of the original `master` or `main` branch. The content of your working directory and index is updated accordingly.
    • Upon committing changes, the `HEAD` moves forward as it continues to point to the latest commit of the branch, updating from the previous commit point.
    • During merge operations, you will typically bring changes from one branch back into `master` or `main`. Here, `HEAD` might point to a temporary merge commit when you are resolving conflicts or reviewing combined changes before the final merge.
  • Detached HEAD state: Sometimes, the `HEAD` can be detached, meaning it doesn't point to any branch but a specific commit instead. You might end up in this state after checking out a specific commit hash. To return to a branch state, simply checkout a branch again.
  • Resetting `HEAD`: The `git reset` command can be used with `HEAD` to adjust the working directory and index by resetting to a different commit, which can be particularly useful in fixing mistakes or clearing incidental changes.

Course illustration
Course illustration

All Rights Reserved.