Cloud Explainers
Home › Git

How to Fix Git 'Detached HEAD' State

Git7 min video

Git's 'detached HEAD' state for beginners, on a real repository: what HEAD is (the .git/HEAD file naming a branch, or a commit when detached), how a tag, a commit ID or origin/main puts you there, why a commit made there vanishes from git log when you switch away, how git reflog and git branch get it back, and how git switch -c keeps you from losing one.

Where did the commit go?

Git says you are in detached HEAD state, and the commit you made there seems to disappear. It almost certainly hasn't, and your fix is coming right up. Jess keeps a steam railway's timetable website. When she committed a fix, Git printed detached HEAD where a branch name usually goes, then the commit's ID. To be fair, Git had warned her. In a paragraph.

Jess's commit, as Git printed it: diagram of [detached HEAD ea050c9], detached HEAD = no branch, ea050c9 = commit ID, Not gone: it can come back

Then she switched back to her main branch. Git said she'd left one commit behind, and her history graph no longer shows it. So where did it go? First, the fixes.

Jess's laptop: ~/timetable
git switch mainWarning: you are leaving 1 commit behind, not connected to
any of your branches:

  ea050c9 Fix the Sunday departure time

If you want to keep it by creating a new branch, this may be a good time
to do so with:

 git branch <new-branch-name> ea050c9

Switched to branch 'main'
Your branch is up to date with 'origin/main'.
Jess's laptop: ~/timetable
git log --oneline --graph --all* 78c1bc2 (HEAD -> main, origin/main, origin/HEAD) Add the booking page
* 7c68053 Add the Santa Specials page
* 2289b49 (tag: v1.2) Winter timetable
* 6d6b645 (tag: v1.1) Add Sunday trains
* a461fa3 (tag: v1.0) First timetable

Haven't committed anything? git switch main takes you back, and nothing is lost. Committed, and still detached? Run git switch -c, then a new branch name. That creates a branch that keeps those commits. Already left, like Jess? Run git reflog, Git's record of everywhere HEAD has been, to find the commit's ID. Then run git branch with a new name and that ID.

Three ways out, by situation: cards of Nothing committed, Committed, still here, Already left: find it, Then name it

What HEAD points to

So what is HEAD? Picture a book with a ribbon bookmark sewn in. A branch is the ribbon: every new commit moves it forward a page. HEAD is your finger. Normally your finger rests on the ribbon, so it moves along with it. Detached HEAD is your finger pressed on one page, off the ribbon. You can still write new pages there, but the ribbon doesn't follow them.

HEAD is your finger, a branch is the ribbon: diagram of HEAD, normally, branch: main, newest commit, an older commit, HEAD, detached

Here's Jess's history: five commits, each shown by the first seven characters of its ID. Three carry tags. A tag is a fixed label on one commit, and unlike a branch it never moves. v1.2 is the winter timetable, printed on the station's posters. Git keeps HEAD in a tiny file, and it just names a branch: main. Each branch is a tiny file too. Main's file holds one full commit ID, the newest one.

Jess's laptop: ~/timetable
git log --oneline --decorate78c1bc2 (HEAD -> main, origin/main, origin/HEAD) Add the booking page
7c68053 Add the Santa Specials page
2289b49 (tag: v1.2) Winter timetable
6d6b645 (tag: v1.1) Add Sunday trains
a461fa3 (tag: v1.0) First timetable
Jess's laptop: ~/timetable
cat .git/HEADref: refs/heads/main
Jess's laptop: ~/timetable
cat .git/refs/heads/main78c1bc23c42af60a7caf50d3683d72bde898967f

Her fellow volunteer Joe asks what the posters say for Sunday, so Jess checks out version one point two, which puts her files back as they were at that tag. Git answers with a whole note. In part, it says: you are in detached HEAD state. You can look around and make experimental commits, and throw them away by switching back. And in the middle, it already names the fix, git switch -c.

Jess's laptop: ~/timetable
git checkout v1.2Note: switching to 'v1.2'.

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 by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 2289b49 Winter timetable

Here's what changed in that tiny file. It no longer names a branch. It holds the commit's full ID instead. That's all detached means: HEAD points straight at a commit, not at a branch.

The whole difference, in one file: code change of .git/HEAD, 2289b49590f75f5b4264b8d1faf5580ad4535c37 (detached at v1.2), Detached: HEAD names a commit, not a branch

git status says it plainly: HEAD detached at v1.2. git branch normally stars the branch you're on. Here the star sits on a placeholder in brackets, because she's on no branch at all. And the file says the Sunday train leaves at 11:30. The real winter train leaves at 11:45.

Jess's laptop: ~/timetable
git statusHEAD detached at v1.2
nothing to commit, working tree clean
Jess's laptop: ~/timetable
git branch* (HEAD detached at v1.2)
  main
Jess's laptop: ~/timetable
cat timetable.html<h1>Oak Hill Steam Railway: winter</h1>
<p>Saturday: 10:15 Oak Hill to Millbrook</p>
<p>Sunday: 11:30 Oak Hill to Millbrook</p>
<p>Last train: 15:40</p>

So she edits that line right here, and commits: dash a takes every changed file, dash m adds the message. It works. The last three commits show the fix sitting on top of version one point two. But look at the brackets on the fix's line: only HEAD points at it. No branch does.

Jess's laptop: ~/timetable
git commit -am 'Fix the Sunday departure time'[detached HEAD ea050c9] Fix the Sunday departure time
 1 file changed, 1 insertion(+), 1 deletion(-)
Jess's laptop: ~/timetable
git log --oneline --decorate -3ea050c9 (HEAD) Fix the Sunday departure time
2289b49 (tag: v1.2) Winter timetable
6d6b645 (tag: v1.1) Add Sunday trains

Here's what happened when she left. Right after her commit, HEAD was the only thing pointing at the fix. When she switches to main, HEAD moves onto the main branch. Nothing points at the fix now. No branch, no tag, and not HEAD. git log starts from those names and follows each commit back to the one before it, so it never reaches the fix. That's why the fix seems to vanish.

Nothing points at the fix any more: diagram of v1.0, v1.1, v1.2, Santa page, Booking page, main, Sunday fix, HEAD, before, HEAD, after

Getting the commit back

Back to Jess's missing fix. Her history graph doesn't show it, because it follows branches and tags. But Git keeps a second diary, called the reflog: every place HEAD has been. The top line is her switch to main. The next line is her commit, with its ID.

Jess's laptop: ~/timetable
git reflog -378c1bc2 (HEAD -> main, origin/main, origin/HEAD) HEAD@{0}: checkout: moving from ea050c9a14c3a6b6872ef6ef2a2acc407bc01cd1 to main
ea050c9 HEAD@{1}: commit: Fix the Sunday departure time
2289b49 (tag: v1.2) HEAD@{2}: checkout: moving from main to v1.2

How long is it safe there? Git's manual says a commit with nothing pointing at it is eventually deleted. That's garbage collection, Git's routine cleanup. Give it a name first, and it's safe. While the reflog still lists the commit, Git won't delete it, and the git gc page gives the time. Guess first: how long does Git keep a reflog entry like Jess's? Thirty days, by default. So rescue a lost commit soon.

Getting the commit back: browser screenshot from the video

Jess checks it's the right commit: git show lists one file changed, the timetable. Then she runs git branch sunday-fix, followed by that ID. Git prints nothing, but now a name points at the fix, and the graph draws it again, branching off version one point two.

Jess's laptop: ~/timetable
git show --stat --oneline ea050c9ea050c9 Fix the Sunday departure time
 timetable.html | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Jess's laptop: ~/timetable
git branch sunday-fix ea050c9
Jess's laptop: ~/timetable
git log --oneline --graph --all* 78c1bc2 (HEAD -> main, origin/main, origin/HEAD) Add the booking page
* 7c68053 Add the Santa Specials page
| * ea050c9 (sunday-fix) Fix the Sunday departure time
|/
* 2289b49 (tag: v1.2) Winter timetable
* 6d6b645 (tag: v1.1) Add Sunday trains
* a461fa3 (tag: v1.0) First timetable

She's back on main, so merging the new branch brings the fix in. One file changed, and a search of main's timetable for Sunday now finds 11:45.

Jess's laptop: ~/timetable
git merge sunday-fixMerge made by the 'ort' strategy.
 timetable.html | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
Jess's laptop: ~/timetable
grep Sunday timetable.html<p>Sunday: 11:45 Oak Hill to Millbrook</p>

Other ways in

Maybe you never checked out a tag, and you're still detached. Here's how that usually happens. Check out a commit ID, maybe to look at an old version, and HEAD detaches. git switch -, a single dash, takes you straight back. Check out origin/main, your read-only copy of the server's branch, and it detaches again. And during a rebase, which replays your commits onto a newer starting point, Git detaches HEAD for a moment on its own, then puts it back. That one needs nothing from you.

Jess's laptop: ~/timetable
git checkout 2289b49Note: switching to '2289b49'.

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 by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 2289b49 Winter timetable
Jess's laptop: ~/timetable
git switch -Previous HEAD position was 2289b49 Winter timetable
Switched to branch 'main'
Your branch is up to date with 'origin/main'.
Jess's laptop: ~/timetable
git checkout origin/mainNote: switching to 'origin/main'.

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 by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 78c1bc2 Add the booking page
Jess's laptop: ~/timetable
git statusHEAD detached at origin/main
nothing to commit, working tree clean

Never lose one again

So how do you never lose one? First, the newer command, git switch, is stricter. Ask it for a tag, and it refuses: a branch is expected. The hint says add --detach if you really mean it. That refusal is a good thing. You can't end up detached by accident.

Jess's laptop: ~/timetable
git switch v1.2fatal: a branch is expected, got tag 'v1.2'
hint: If you want to detach HEAD at the commit, try again with the --detach option.

Better still, start on a branch. git switch -c poster-fix v1.2: dash c creates a branch called poster-fix, starting at the poster version, and puts HEAD on it. The HEAD file names that branch, so every commit from here moves the ribbon.

Jess's laptop: ~/timetable
git switch -c poster-fix v1.2Switched to a new branch 'poster-fix'
Jess's laptop: ~/timetable
cat .git/HEADref: refs/heads/poster-fix

Recap

So: detached HEAD means HEAD names a commit, not a branch. Nothing committed? git switch main. Committed? git switch -c and a new name, before you leave. Already left? git reflog, then git branch.

Detached HEAD, fixed: cards of What it means, Nothing committed, Committed, Already left

If this got a commit of yours back, subscribing brings more Git fixes.

All the lab files and commands are linked in the description. Thanks for watching Cloud Explainers.

Sources

Demos: one container on our own Mac standing in for a laptop, with a local shared repository; the railway and its timetable are made up. Every command, output and commit ID was real. Watch the full video on YouTube.

More videos

PostgreSQL9 min

Every PostgreSQL Setting to Change After You Install It

Docker9 min

What Happens When You Install Docker on Ubuntu

Python8 min

How to Fix Python 'Address Already in Use' Errors

Go (Golang)5 min

Golang Interfaces and Mocks in 5 Minutes

Linux21 min

Linux Firewall with ufw: Full Tutorial for Beginners

Go (Golang)5 min

Golang defer Statements in 5 Minutes

Auth (OAuth, JWT)9 min

How to Fix OAuth 'invalid_grant' Errors

Databases & SQL11 min

The SQL Roadmap for Beginners

Go (Golang)5 min

Golang make() for Slices and Maps in 5 Minutes

Networking7 min

How to Fix Network 'No Route to Host' Errors on Linux

Linux6 min

How to Fix Linux 'Too Many Open Files' Errors

Django (Python web framework)11 min

Every Django Concept a Beginner Needs to Know

Linux24 min

SSH on Linux: Full Tutorial for Beginners

Go (Golang)5 min

Golang for range Loops in 5 Minutes

Databases & SQL10 min

SQL Databases: SQLite vs PostgreSQL

Django (Python web framework)10 min

The Django Roadmap for Beginners

Go (Golang)5 min

Golang Structs in 5 Minutes

Caching & Redis22 min

Redis: Full Tutorial for Beginners

Go (Golang)5 min

Golang context.Context in 5 Minutes

Databases & SQL7 min

How to Fix MySQL Database Error 1045: Access Denied for User

Go (Golang)5 min

Golang Method Receivers in 5 Minutes

Python8 min

How to Fix Python SSL: CERTIFICATE_VERIFY_FAILED Errors

Django (Python web framework)9 min

How to Fix Django Static Files Not Loading in Production

OpenRouter (one API for many AI models)8 min

OpenRouter vs Direct API Keys: Which One Should You Use?

Go (Golang)5 min

Golang if err != nil Checks in 5 Minutes

Go (Golang)8 min

How to Fix Golang 'go.mod File Not Found' Errors

AI agents & MCP22 min

MCP Servers: Full Tutorial for Beginners

Go (Golang)5 min

Golang Error Return Values in 5 Minutes

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index