Git Detached Head: What This Means and How to Recover

409
CloudBees
CloudBees, the enterprise software delivery company, provides the industry’s leading DevOps technology platform. CloudBees enables developers to focus on what they do best: Build stuff that matters, while providing peace of mind to management with powerful risk mitigation, compliance and governance tools.

The following is a guest blog post written by Carlos Schults.

Newcomers to Git often get confused with some of the messages that the VCS tool throws at them. The “You are in ‘detached HEAD’ state” one is certainly one of the weirdest. After coming across this message, most people start furiously Googling “git detached HEAD,” “git detached HEAD fix,” or similar terms, looking for anything that might be of help. If that’s your case, you’ve come to the right place.

Here’s the first thing you should know: you haven’t done anything wrong. Your repo isn’t broken or anything like that. The expression “Detached HEAD” might sound somewhat bizarre, but it’s a perfectly valid repository state in Git. Sure, it’s not the normal state, which would be—you’ve guessed it!—when HEAD is attached. The second thing you need to know is that going back to normal is super easy. If you just want to do that and get on with your day, go to the “How Do I Fix a Detached Head in Git?” section of this post to see how it’s done.

But if you want to know more—and I guess you do—stick around and we’ll help you. What does HEAD mean in Git? What does it mean for it to be attached or detached? These are the kind of questions we’ll answer in this post. By the end of it, you’ll have a better understanding of Git’s fundamentals, and detached HEADs will never trouble you again. Let’s dig in.

Git Detached HEAD: Reproducing the “Problem”

Let’s start with a quick demo showing how to reach the detached HEAD state. We’ll create a repository and add some commits to it:

mkdir git-head-demo
cd git-head-demo
git init
touch file.txt
git add .
git commit -m "Create file"
echo "Hello World!" > file.txt
git commit -a -m "Add line to the file"
echo "Second file" > file2.txt
git add .
git commit -m "Create second file"

With the commands above, we’ve created a new folder with a new repository inside it. Then we created a new empty file and committed that with the message “Create file.” Next, we added a line to that file and committed the change, with the message “Add a line to the file.” Finally, we’ve created another file with one line of text and committed that as well. If you use the git log –oneline command, you’ll see something like this:

Let’s say that, for testing purposes, we need to see how things were at the time of the second commit. How would we do that? As it turns out, we can check out a commit the same way we’d check out branches. Remember, branches are just names for commits. So, based on the example output above, we’d run git checkout 87ec91d. Keep in mind that if you’re following along by executing these commands on your own system, the hash for your commits will be different from those in the example. Use the log command to find it.

After running the command, we get the “You are in ‘detached HEAD’ state[…]” message. Before we go on, make sure you keep this in mind: you get to the detached HEAD state by checking out a commit directly.

What Is a HEAD in Git?

What does HEAD mean in Git? To understand that, we have to take a step back and talk fundamentals.

A Git repository is a collection of objects and references. Objects have relationships with each other, and references point to objects and to other references. The main objects in a Git repository are commits, but other objects include blobs and trees. The most important references in Git are branches, which you can think of as labels you put on a commit.

HEAD is another important type of reference. The purpose of HEAD is to keep track of the current point in a Git repo. In other words, HEAD answers the question, “Where am I right now?”

For instance, when you use the log command, how does Git know which commit it should start displaying results from? HEAD provides the answer. When you create a new commit, its parent is indicated by where HEAD currently points to.

Are you in ‘detached HEAD’ state?

You’ve just seen that HEAD in Git is only the name of a reference that indicates the current point in a repository. So, what does it mean for it to be attached or detached?

Most of the time, HEAD points to a branch name. When you add a new commit, your branch reference is updated to point to it, but HEAD remains the same. When you change branches, HEAD is updated to point to the branch you’ve switched to. All of that means that, in these scenarios, HEAD is synonymous with “the last commit in the current branch.” This is the normal state, in which HEAD is attached to a branch.

A visual representation of our demo repository would look like this:

As you can see, HEAD points to the master branch, which points to the last commit. Everything looks perfect. After running git checkout 87ec91d, the repo looks like this:

This is the detached HEAD state; HEAD is pointing directly to a commit instead of a branch.

Benefits of a Git Detached HEAD

Are there good reasons for you to be in the detached HEAD state? You bet there are!

As you’ve seen, you detach the HEAD by checking out a commit. That’s already useful by itself since it allows you to go to a previous point in the project’s history. Let’s say you want to check if a given bug already existed last Tuesday. You can use the log command, filtering by date, to start the relevant commit hash. Then you can check out the commit and test the application, either by hand or by running your automated test suite.

What if you could not only take a look at the past, but also change it? That’s what a detached HEAD allows you to do. Let’s review how the detached message starts:

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.

In this state, you can make experimental changes, effectively creating an alternate history. So, let’s create some additional commits in the detached HEAD state and see how our repo looks afterward:

echo "Welcome to the alternate timeline, Morty!" > new-file.txt
git add .
git commit -m "Create new file"
echo "Another line" >> new-file.txt
git commit -a -m "Add a new line to the file"

We now have two additional commits that descend from our second commit. Let’s run git log –oneline and see the result:

This is what the diagram looks like now:

What should you do if you want to keep those changes? And what should you do if you want to discard them? That’s what we’ll see next.

How Do I Fix a Detached HEAD in Git?

You can’t fix what isn’t broken. As I’ve said before, a detached HEAD is a valid state in Git. It’s not a problem. But you may still want to know how to get back to normal, and that depends on why you’re in this situation in the first place.

Scenario #1: I’m Here by Accident

If you’ve reached the detached HEAD state by accident—that is to say, you didn’t mean to check out a commit—going back is easy. Just check out the branch you were in before:

git checkout <branch-name>

If you’re using Git 2.23.0 or newer, you can also use switch instead of checkout:

git switch <branch-name>

Scenario #2: I’ve Made Experimental Changes and I Want to Discard Them

You’ve entered the detached HEAD state and made a few commits. The experiment went nowhere, and you’ll no longer work on it. What do you do? You just do the same as in the previous scenario: go back to your original branch. The changes you made while in the alternate timeline won’t have any impact on your current branch.

Scenario #3: I’ve Made Experimental Changes and I Want to Keep Them

If you want to keep changes made with a detached HEAD, just create a new branch and switch to it. You can create it right after arriving at a detached HEAD or after creating one or more commits. The result is the same. The only restriction is that you should do it before returning to your normal branch.

Let’s do it in our demo repo:

git branch alt-history
git checkout alt-history

Notice how the result of git log –oneline is exactly the same as before (the only difference being the name of the branch indicated in the last commit):

We could just run git branch alt-history, and we’d be all set. That’s the new—and final—version of our diagram:

Getting Rid of the “Git Detached HEAD” Message

Before wrapping up, let’s share a final quick tip. Now that you understand everything about detached HEAD in Git and know that it’s not that big of a deal, seeing that message every time you check out a commit might become tiring. Fortunately, there’s a way to not see the warning anymore. Just run the following command:

git config advice.detached head false

Easy, right? You can also use the –global modifier if you want the change to apply to every repository and not only the current one.

Git Detached HEAD: Less Scary Than It Sounds

A message talking about heads not being attached doesn’t sound like your routine software error message, right? Well, it’s not an error message.

As you’ve seen in this post, a detached HEAD doesn’t mean something is wrong with your repo. Detached HEAD is just a less usual state your repository can be in. Aside from not being an error, it can actually be quite useful, allowing you to run experiments that you can then choose to keep or discard.

Carlos Schults is a .NET software developer with experience in both desktop and web development, and he’s now trying his hand at mobile. He has a passion for writing clean and concise code, and he’s interested in practices that help you improve app health, such as code review, automated testing, and continuous build.

CloudBees
CloudBees, the enterprise software delivery company, provides the industry’s leading DevOps technology platform. CloudBees enables developers to focus on what they do best: Build stuff that matters, while providing peace of mind to management with powerful risk mitigation, compliance and governance tools.
Tools mentioned in article
Open jobs at CloudBees
Development Support Engineer
United States or Canada

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.
 
CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.
  
Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.
 
CloudBees is home to the world’s leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great idea, to great software, to great business value.

What You’ll Do

Provide software technical support to developers and configuration managers on the CloudBees products. This includes communicating directly with customers via our support portal. This is however, much more than just a “support” position.

  • Ability to analyze scenarios of software implementations and provide solutions for problems
  • Set correct priorities for ongoing issues
  • Work with the CloudBees development team to improve products and/or resolve customer issues
  • Work with other software partners to resolve customer issues
  • At times, work in high pressure situations such as “customer down” priority scenarios to resolve issues timely and professionally
  • The support engineer must be well-rounded in IT skills, the ability to use a wide range of that knowledge at any given time is crucial
  • Capable of working in a fast-paced environment

What The Role Requires

  • Degree in computer science / IT – or – equivalent experience
  • Trouble shooting skills with multi-threaded applications (debugging, analyzing a thread dump, troubleshooting
  • Jenkins user (setting up release processes, for example)
  • Measurable level of experience in multiple operating systems (Windows, Linux, OS X)
  • Measurable level of experience with continuous integration. Jenkins experience preferred
  • Measurable level of experience with Docker, AWS and Configuration Management tools (Chef, Puppet, etc...) 
  • Basic knowledge of shell scripting (CMD, KSH)

What You’ll Get

  • Highly competitive benefits and vacation package
  • Ability to work for one of the fastest growing companies with some of the most talented people in the industry
  • Team outings
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers. A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers. Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage. CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers. CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

 

Operations Engineer
Raleigh, NC, Boston, MA, US East

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.

 CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.

Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.

CloudBees is home to the world’s leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great idea, to great software, to great business value.

To support the delivery of the CloudBees engineering projects - the Operations team designs, deploys and manages a variety of software systems and the related AWS infrastructure that underpins this software.

CloudBees has an Operations team that is available around the clock (in their respective time zones!) to deliver a highly available service to our growing engineering teams.

One of your first tasks will be to integrate with the engineering teams to deliver the infrastructure required to deploy their projects - “Embedded Ops” - this role helps deliver infrastructure that meets the Engineering project’s needs while conforming to Operations guidelines for long term maintenance and reliability.

What You'll Do

  • Collaborate with existing project operations and CloudBees operations team members to ensure solutions fit into exists patterns.
  • Design, development, integration, testing and delivery of infrastructure for engineering teams.
  • Ongoing operational design and implementation work CloudBees infrastructure
  • Handle operational incidents from initiation to resolution
  • Drive architecture for major feature areas and drive decisions regarding key technologies
  • Troubleshoot and debug software and infrastructural components including application of root cause analysis to find faults.
  • Contribute fixes and enhancements to the open source projects
  • Tuning of monitoring, system design and alerting to reduce alert quantity, increase alert quality and ultimately eliminate alert fatigue.
  • Assist with escalated support incidents
  • Report to the CloudBees IT Operations Manager on status of system faults and deliverables
  • Ability to follow processes and complete work within a change controlled environment

What the Role Requires 

  • Self-motivated and driven personality
  • Excellent problem solving and communication skills
  • Ability to operate independently and ask questions when stuck
  • Well-rounded experience programming in various languages and domains
  • Linux systems administration experience
  • Experience with cloud-based operations (e.g. AWS,  Azure, GCP)
  • Familiarity with the "modern Ops stack", e.g. monitoring, alerting, cloud-based provisioning, Docker.
  • Experience/understanding of configuration management tools
  • Experience/familiarity with modern software engineering practices: code reviews, unit/acceptance testing, source control, etc.
  • Experience with cluster orchestration tools (e.g. Cloud Formation / k8s / ECS / Terraform / etc)
  • Experience with continuous integration / continuous delivery tools (Jenkins / Bamboo / TeamCity etc)

What You’ll Get

  • A highly competitive benefits and vacation package
  • The opportunity to work for one of the fastest growing companies with some of the most talented people in the industry
  • Cool team outings (To Málaga for instance!)
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers. A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers. Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage. CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers. CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

Remote DevOps Consultant
United States

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.
 
CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.
  
Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.
 
CloudBees is home to the world’s leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great idea, to great software, to great business value.

As a DevOps Consultant, you will be the primary operational point of contact for one or more enterprise customers, helping to plan, review, and monitor ongoing operations of our customers Continuous Delivery pipeline. You will leverage your broad experience, troubleshooting application and architectural challenges to support our customers. You will work across customer organizations to ensure customers’ Continuous Integration (CI) / Continuous Delivery (CD) solution is well designed and scalable to their needs. In this role, you will also act as the voice of the customer within CloudBees to escalate problems and to drive prioritization of business needs for our customers.

What You'll Do

  • Champion and advocate for enterprise customers within CloudBees (be their voice)
  • Solve technical issues and work directly with CloudBees engineers to ensure that customer issues are resolved as expediently as possible
  • Participate in deep architectural discussions, calling on CloudBees subject matter experts as needed, to ensure solutions are designed for successful deployment
  • Help enterprise customers define IT and business processes that work well with CI/CD deployments
  • Engage with Director and C-Level executives to translate business needs into technical and operational plans
  • Provide detailed reviews of service metrics to customer leadership

What The Role Requires

  • Jenkins CI experience required
  • 5+ years in a DevOps, Release Engineering, or Software Engineering role
  • Willingness to learn Docker and MicroServices
  • Experience managing large scale environments including escalations, incident, problem, and service availability
  • Customer-facing experience as a technical lead
  • High level of comfort communicating effectively across internal and external organizations
  • Presentation skills; high degree of comfort with both large and small audiences
  • Bachelor’s degree or equivalent work experience required; Computer Science or Math background highly desired; working knowledge of software development practices and technologies highly desired
  • Software design, development and deployment
  • Occasional travel to visit your customers

What You’ll Get

  • Highly competitive benefits and vacation package
  • Ability to work for one of the fastest growing companies with some of the most talented people in the industry
  • Industry Certifications
  • Team outings
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers. A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers. Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage. CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers. CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

Senior Software Engineer
Raleigh, NC, Boston, MA, or

Our Customers Develop Software at the Speed of Ideas

CloudBees is powering the continuous economy by offering the world’s first end-to-end continuous software delivery management system (SDM). For millions of developers and product teams driving innovation for businesses large or small, SDM builds on continuous integration (CI) and continuous delivery (CD) to enable all functions and teams within and around the software delivery organization to best work together to amplify value creation.
 
CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and its open source leadership as the largest contributor to Jenkins and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 500 employees, the company reflects the global nature of the DevOps movement. We believe in walking the talk! From startups with full-stack developers practicing NoOps to large Fortune 100 companies, CloudBees enables all software-driven organizations to intelligently deploy the right capabilities at the right time.
  
Over 3,500 of the world’s best known brands and over 50% of the Fortune 500, invest in CloudBees because of its ability to work across any cloud, in any development environment and to balance corporate governance and control with developer flexibility and freedom.
 
This role will focus on working with Jenkins and the CloudBees package offerings as well as the many plugins that CloudBees creates to enhance the Jenkins experience. You’ll be responsible to help build out enhancements to Jenkins by way of plugins as well as maintain the existing enhancements that CloudBees has already provided.

What You’ll Do

  • Support and enhance the Jenkins experience for our customers by way of its rich plugin system
  • Work as a contributor in the Jenkins open-source community, deliver fixes and enhancements to the Jenkins open source project specifically around the various plugins
  • Collaborate with CloudBees customers when needed to help define requirements and help them solve challenging issues
  • Collaborate with the Jenkins Security Team to cross reference the priorities of items to address
  • Collaborate with product management, support and engineering teams in order to define priorities and roadmaps

What The Role Requires

  • 5+ years experience developing with Java.
  • Demonstrated implementation of microservices, container and cloud-native application development.
  • Hands-on experience with Docker, Kubernetes or Openshift and related container platform ecosystems.
  • Strong understanding and experience of release engineering and continuous delivery process
  • Strong understanding of static code analysis, unit testing and test driven development, security testing and automated test frameworks.
  • Experience using Jenkins, SonarQube, GIT, Maven.
  • Solid understanding of Amazon Web Services; Azure, Google Cloud a plus.
  • Nice to have: contributions to the Jenkins Project or Jenkins plugins
  • Knowledge of developer tools such as Continuous Integration/Continuous Delivery systems, test tools, code quality tools, planning tools, IDEs and debugging tools
  • Excellent problem solving and communication skills
  • Ability to be self sufficient given the proper guidance
  • Fully proficient in English written and spoken language
  • Comfortable working closely with support, customers and community to help resolve issues

Why CloudBees?

  • We build our business on Jenkins by offering enterprise solutions (CloudBees CI) and professional services, our customers range from the blue chips to small innovative companies
  • We work on various projects in different areas. We are flexible about changing teams and assignments according to the interest and passion of engineers.
  • Our Engineering teams are distributed by design. You can work from the office or remotely without feeling disconnected.
  • You have an opportunity to contribute to open-source projects and communities during your working time.
  • We offer an attractive benefits package including stock options.

What You’ll Get

  • Highly competitive benefits and vacation package
  • Ability to work for one of the fastest growing companies with some of the most talented people in the industry
  • Team outings
  • Fun, Hardworking, and Casual Environment
  • Endless Growth Opportunities

At CloudBees, we truly believe that the more diverse we are, the better we serve our customers.  A global community like Jenkins demands a global focus from CloudBees. Organizations with greater diversity—gender, racial, ethnic, and global—are stronger partners to their customers.  Whether by creating more innovative products, or better understanding our worldwide customers, or establishing a stronger cross-section of cultural leadership skills, diversity strengthens all aspects of the CloudBees organization.

In the technology industry, diversity creates a competitive advantage.  CloudBees customers demand technologies from us that solve their software development, and therefore their business problems, so that they can better serve their own customers.  CloudBees attributes much of its success to its worldwide work force and commitment to global diversity, which opens our proprietary software to innovative ideas from anywhere. Along the way, we have witnessed firsthand how employees, partners, and customers with diverse perspectives and experiences contribute to creative problem solving and better solutions for our customers and their businesses.

You may also like