Git Detached Head: What This Means and How to Recover

1,316
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
Remote DevOps Consultant
US

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

  • 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

  • Knowledge of and experience with current DevOps industry practices
  • Understanding of REST API, SOAP, Perl, Python, Groovy
  • Strong Linux command line knowledge
  • Strong software architecture knowledge
  • Conducts solution analysis, testing, and provides guidance on common industry practices and technologies
  • Able to collaborate with multiple cross-functional groups at once
  • Working knowledge of SDLC pipeline functions including CI, build methods, code scanning, testing, artifact repositories, release management, deployment automation and infrastructure platforms
  • Can model SDLC to describe the process from concept to delivered solution
  • Able to coordinate and conduct discovery and analysis of current state including process, culture and technology capabilities
  • Can collate and refine detailed functional and nonfunctional requirements in order to inform future state design

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.

Software Engineer-Jenkins Security
EMEA

OUR CUSTOMERS DEVELOP SOFTWARE AT THE SPEED OF IDEAS

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. Used by many of the Fortune 100, CloudBees is helping thousands of companies harness the power of continuous everything and gets them on the fastest path from a great idea, to great software, to amazing customer experiences, to being a business that changes lives.

Backed by Matrix Partners, Lightspeed Venture Partners, Verizon Ventures, Delta-v Capital, Golub Capital, and Unusual Ventures, CloudBees was founded in 2010 by former JBoss CTO Sacha Labourey and an elite team of continuous integration, continuous delivery, and DevOps professionals.

What You’ll Do

  • Learn the internals of Jenkins and its plugin system from the perspective of web application security
  • Participate in the Jenkins CERT
    • Detect and correct vulnerabilities
    • Review, coordinate and deliver corrections
  • Security architecture
    • Make deep/chirurgical changes into Jenkins core
    • Assess/evaluate security risks, not only in Jenkins but also in other project in the product department
  • Engineer and automate our security tooling/process
    • Improve our capacities to search patterns in the ecosystem
    • Automate as much as we can the vulnerability detection
  • Security support
    • Analyse scanner reports
    • Use/improve our vulnerability management application (OWASP DefectDojo)
    • Reply to customer/support questions about security
    • Participate in meetings with customers to understand their requirements
  • Security education
    • Provide help to other teams, assessing vulnerabilities, reviewing corrections
    • Improve security awareness
    • Provide training / demo
  • Participate in the industry events
    • Learn the latest trends in security
    • Share the learning from this role to the wider community during talks and workshops
  • Our Engineering teams are distributed by design. You can work from the offices or remotely without feeling disconnected

What The Role Requires

  • Knowledge & passion for web application security (OWASP Top 10)
  • Solid experience in Java web application development (JavaScript is a plus)
  • Experience in scripting (Groovy, Shell, Python)
  • Hacker mindset
    • Willingness to learn
    • Desire to break things for the good
    • Solving problems
  • Proficiency using CI/CD tools

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

We have a culture of movers and shakers and are leading the way for everyone else with a vision to transform the industry. We are authentic in who we are. We believe in our abilities and strengths to change the world for the better. Being inclusive and working together is at the heart of everything we do. We are naturally curious. We ask the right questions, challenge what can be done differently and come up with intelligent solutions to the problems we find. If that’s you, get ready to bee impactful and join the hive.

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 workforce 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 business.

Development Support Engineer
US

Our Customers Develop Software at the Speed of Ideas

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. Used by many of the Fortune 100, CloudBees is helping thousands of companies harness the power of continuous everything and gets them on the fastest path from a great idea, to great software, to amazing customer experiences, to being a business that changes lives.

Backed by Matrix Partners, Lightspeed Venture Partners, Verizon Ventures, Delta-v Capital, Golub Capital, and Unusual Ventures, CloudBees was founded in 2010 by former JBoss CTO Sacha Labourey and an elite team of continuous integration, continuous delivery, and DevOps professionals.

Team description

CloudBees customers rely on our Support team to help them be successful in the use of our products. Our team is uniquely positioned to help sustain the company’s growth by providing a customer support experience that surpasses expectations. These positive customer experiences help drive annual renewals and business expansion. A successful Development Support Engineer (DSE) will use their skills and experience to accurately diagnose customer issues and get them resolved in a timely way, to the customer’s satisfaction. In addition, motivated individuals who want to contribute in other ways will have opportunities to work on our collection of internal tools that automate the diagnosis of issues, making the entire team more efficient by reducing manual work.

A typical day in our Support team starts with a scrum meeting where we review open and unassigned cases and help each other with issues we’re stuck on. Working on active cases, we answer basic questions and also troubleshoot problems that range from the mundane to the fiendishly complicated (it helps if you enjoy a good challenge). We collaborate with each other throughout the day, via Slack or video calls. During down time, we build technical knowledge through training and tools development.

CloudBees has been a remote-work-first company since it was founded, and the majority of the DSE team works remotely. The existing team has a mix of backgrounds including system administrators, developers, support engineers, and devops engineers. We strive to provide everyone on the team with interesting challenges, opportunities for personal and professional growth, and a positive work/life balance.

What You'll Do 

  • Answer customer questions about product usage and best practices
  • Diagnose complex technical issues and provide solutions or workarounds
  • Communicate with customers through a ticketing system, with phone support sometimes required for complex or urgent issues
  • Collaborate frequently with members of the Support and Engineering teams
  • Contribute to documentation
  • Contribute to internal software tools to automate diagnosis of customer issues
  • Work a weekend on-call rotation every 4-8 weeks (daytime hours only)

What The Role Requires 

A successful candidate will have:

  • Basic Linux system administration knowledge
  • Good communication skills (English language fluency required)
  • The ability to work independently
  • The ability to build knowledge of new technologies easily
  • A sense of empathy with our customers

As previously mentioned, members of our team have a variety of past work experience, and each bring a different mix of skills to our team. The following are some examples of these skills, but by no means do we expect candidates to have all of them. If any of these fit with your experience, we would love to hear from you!

  • System administration knowledge, especially Linux, storage, and/or networking
  • Good working knowledge of popular DevOps tools and services such as: Jenkins, Docker, Artifactory/Nexus, Kubernetes, git & GitHub
  • Knowledge of common enterprise environments & technologies such as LDAP & databases
  • Knowledge of common web application architectures, SSL, REST API concepts, etc.
  • Understanding of Continuous Integration and Continuous Deployment concepts and practices
  • Experience with cloud computing environments
  • Programming experience, anything from shell scripting to Java development
  • Open source community contributions, especially Jenkins
  • Previous experience in customer-facing roles
  • Computer Science / IT degree or equivalent work experience
  • Certifications: Cloud computing providers, Kubernetes, etc.

What You'll Get 

  • Gain experience working with and troubleshooting a variety of tools used widely in the tech industry
  • Enhance your career by completing industry-recognized technical certifications
  • Manage projects and initiatives within the team, contributing to team goals
  • Potential future opportunities to grow into management, engineering, or other field roles
  • Play a key role in maintaining and growing company revenue over time

We have a culture of movers and shakers and are leading the way for everyone else with a vision to transform the industry. We are authentic in who we are. We believe in our abilities and strengths to change the world for the better. Being inclusive and working together is at the heart of everything we do. We are naturally curious. We ask the right questions, challenge what can be done differently and come up with intelligent solutions to the problems we find. If that’s you, get ready to bee impactful and join the hive

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.

Associate Solution Architect
US or Canada

OUR CUSTOMERS DEVELOP SOFTWARE AT THE SPEED OF IDEAS

CloudBees is the continuous integration (CI), continuous delivery (CD) and application release automation (ARA) powerhouse built from the commercial success of its products and a founding member of the Continuous Delivery Foundation (CDF). With a globally distributed workforce of more than 450 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 the home for leading DevOps experts helping thousands of companies harness the power of “continuous everything” and putting them on the fastest path from great ideas, to great software, to great business value.

CloudBees is looking for an Associate PreSales Engineer to join the CloudBees sales organization. This role is key for our sales organization. The position involves working side-by-side with the sales team, uncovering and developing opportunities by articulating the technical options for potential customers. While this role requires technology depth and awareness, this is a sales-driven position.  The role carries a quota and directly impacts the revenue of the company. The ideal candidate will have been involved in the continuous integration, continuous delivery and DevOps space with strong interpersonal skills. Prior technical sales positions and experience would be helpful. 

This is an amazing opportunity to become an expert in what’s soon to become the future of software development, and to work closely with recognized experts in the continuous integration, continuous delivery and DevOps markets. 

WHAT YOU'LL DO

  • Become an expert on all things related to Jenkins, continuous integration, continuous delivery and DevOps
  • Serve as a liaison between sales, support, engineering and the customer/prospect
  • Field more advanced user questions to sales for possible upsell to annual/global deals
  • Understand the company’s products, competitors, value proposition and positioning
  • Assist the sales team on calls and e-mail exchanges with prospects
  • Maintain and develop FAQ fed by information from customers, prospects and the sales team
  • When recurring questions are identified, writing technical content to increase the Knowledge Base and creating videos/webcasts and other content
  • Work with the product team to identify product priorities discovered in field engagements
  • Attend trade shows, when appropriate
  • Deliver regular demos of the product (Google Hangout, webcast, etc.)

WHO YOU ARE

  • Bachelor’s degree in related field
  • Hands-on experience with continuous integration and its real-world role in delivering software
  • Familiarity with Jenkins or other CI products/services
  • Understanding of agile development processes and how organizations adopt and implement those processes
  • Familiarity with DevOps and toolchain associated with it, such as Jenkins, Chef, Puppet and other deployment automation technologies
  • At least three years of software development background (Java preferred)
  • Direct experience with application servers and development frameworks
  • Familiarity with continuous integration (e.g., Jenkins), source code control systems (e.g., Git, SVN), build automation tools (Ant, Maven, Gradle, etc.)
  • Up to 50% travel 

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.

Verified by
Technical Evangelist
You may also like