0
0
Gitdevops~5 mins

Detached HEAD state in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes in Git, you might check out a specific commit instead of a branch. This puts you in a detached HEAD state, where changes are not linked to any branch. It helps to explore or test old versions without affecting your main work.
When you want to look at the code as it was at a specific past commit without changing branches
When you want to test or build a previous version of your project temporarily
When you want to create a quick fix or experiment without affecting any branch
When you want to inspect or debug a commit before deciding to create a branch from it
When you accidentally checked out a commit and want to understand what happened
Commands
This command switches your working directory to the commit with hash 1a2b3c4d. It puts you in detached HEAD state because you are not on any branch.
Terminal
git checkout 1a2b3c4d
Expected OutputExpected
Note: switching to '1a2b3c4d'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches. HEAD is now at 1a2b3c4d Commit message here
This shows your current state. It will tell you that you are in detached HEAD state and show any changes you made.
Terminal
git status
Expected OutputExpected
HEAD detached at 1a2b3c4d nothing to commit, working tree clean
This command moves you back to the main branch, exiting detached HEAD state and returning to normal branch work.
Terminal
git checkout main
Expected OutputExpected
Switched to branch 'main' Your branch is up to date with 'origin/main'.
If you want to keep changes made in detached HEAD state, create a new branch from there with this command.
Terminal
git switch -c new-branch
Expected OutputExpected
Switched to a new branch 'new-branch'
-c - Creates and switches to a new branch
Key Concept

If you remember nothing else, remember: Detached HEAD means you are not on a branch, so commits made here can be lost unless you create a branch.

Common Mistakes
Making commits in detached HEAD state and then switching branches without saving them
Those commits become unreachable and can be lost because they are not on any branch
Create a new branch from detached HEAD before switching to save your commits
Confusing detached HEAD with being on a branch
You might think your changes are safe on a branch when they are not linked to any branch
Always check 'git status' to confirm if you are on a branch or detached HEAD
Summary
Use 'git checkout <commit-hash>' to enter detached HEAD state and view a specific commit.
'git status' shows you are in detached HEAD state and your current changes.
Use 'git checkout <branch>' to exit detached HEAD and return to a branch.
Create a new branch with 'git switch -c <branch-name>' to save commits made in detached HEAD.