git,

Git: HEAD vs working tree vs index

Sep 15, 2022 · 2 mins read · Post a comment

Here’s a Git interview question: “What’s the difference between HEAD, working tree and index in Git?”. First, we need to understand the usual Git workflow:

| Working tree | Staging area | .git directory (local repo) | Remote repository |
|--------------|--------------|-----------------------------|-------------------|
        |              |                      |                        |     
        |<--------git checkout----------------|                        |
        |              |                      |                        |
        |-stage files->|                      |                        |
        |              |                      |                        |
        |              |-------commit-------->|                        |
        |              |                      |                        |
        |              |                      |------git push--------->|

Main parts of a Git project: The working tree (directory), the staging area (index), the .git directory (local repo) and the remote repository.

Prerequisites

  • Git

Solution

HEAD is just a pointer to whatever commit or branch you currently have run git checkout. By default, if you checked out from the main branch, HEAD will point to the main branch.

Test it out:

cat .git/HEAD
ref: refs/heads/main

cat .git/refs/heads/main
<main_branch_commit_hash_ID>

working tree (directory)

The working tree or known as the working directory is the file system directory where the code is stored, and the place where you are currently developing a new feature or fixing bugs.

Git-tracked files are in a modified state.

Staging area (index)

The staging area, also known as the index is the place where you store all the files that needs to be committed. This is usually done by running the git add command.

Git-tracked files are in a staged state.

.git directory (local repository)

The most important part where Git saves its metadata and the database related to your project. This is where the “magic happens” once you run git commit. All committed files are stored here in your local repository.

Remote repository

Self-explanatory. This can be a GitHub, GitLab or even self-hosted repo. Once you run git push the changes are uploaded to the remote repo location.

Conclusion

To find more neat Git commands and hacks, browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.

git