Git Detached Head: What This Means and How to Recover

3,217
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
Security Software Engineer in Jenkins...
US East or EMEA

About CloudBees

CloudBees provides the leading software delivery platform for enterprises, enabling them to continuously innovate, compete, and win in a world powered by the digital experience. Designed for the world's largest organizations with the most complex requirements, CloudBees enables software development organizations to deliver scalable, compliant, governed, and secure software from the code a developer writes to the people who use it. The platform connects with other best-of-breed tools, improves the developer experience, and enables organizations to bring digital innovation to life continuously, adapt quickly, and unlock business outcomes that create market leaders and disruptors.

CloudBees was founded in 2010 and is backed by Goldman Sachs, Morgan Stanley, Bridgepoint Credit, HSBC, Golub Capital, Delta-v Capital, Matrix Partners, and Lightspeed Venture Partners. Visit www.cloudbees.com and follow us on Twitter, LinkedIn, and Facebook.

Why this role

We are looking for a highly motivated (security) engineer to join a team focusing on improving the security of Jenkins and CloudBees CI, our Jenkins based product.

What You’ll Do

  • Learn the internals of Jenkins and its plugin system from the perspective of web application security
  • Participate in the Jenkins security team working on the full lifecycle of vulnerabilities
  • Different security aspects: architecture, design, review, implementation
  • Engineer and automate our security tooling/process
  • Security education / awareness
  • Our Engineering teams are distributed by design. You can work from the offices or remotely without feeling disconnected

What The Role Requires

  • Solid experience in Java web application development (JavaScript is a plus)
  • Interest in web application security
  • Experience in scripting is a plus (Groovy, Shell, Python)
  • Hacker mindset
  • Experience using CI/CD tools (Jenkins is a plus)

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.

Business Systems Architect

The Company

A remote first, fast paced, international growing software technology company looking for the best talent to join The Hive during a rapid growth 3 year plan. We are looking for curious, self-driven and talented new team members for an exciting opportunity. 

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.

The role

The Manager, Business Systems Architecture is a leadership role. S/he will be responsible for establishing a strong Business Solution team within Cloudbees. This Business Solution team manages the ongoing use and  integration of various critical third party business systemsIncluding, but not limited to, end-user support, maintenance, development and implementation of reporting and dashboards, workflow modification, and on-going tighter integration among various business systems to increase efficiency and productivity of Cloudbees business operations. Although this position is in the Business Systems organization, the individual works closely with subject matter experts in Sales, Marketing, Product, and other business areas to identify, deploy, and maintain both existing and new features and functionality to support the entire organization.

 

Main responsibilities:

  • Provide strategy, integration, and operation expertise on business solution systems such as Salesforce, Gainsight, Atlassian, Zendesk, Oracle, Marketo, NetSuite, Celigo, Clari, Dun & Bradstreet etc.
  • Review business requirements from various departments, analyze requirements, design solution, and develop project plan 
  • Collaborate with various people in different departments and able to sell ideas, design proposal, and project plan effectively
  • Complete regular internal system audits and prepare for upgrades
  • Coordinate the evaluation, scope and completion of new integration or upgrade projects
  • Work independently with members of the user community to define and document business and functional requirements.
  • Execute new functionality in coordination with the Business Systems team and impacted teams in the user community
  • Partner with various business teams/departments with evaluation of appexchange connectors to support expanding organization requirements

 

Reporting structure:

  • This role is within Business Operations department
  • Business Operations department provides Cloudbees the ability to monitor and manage its business through real-time data and provide scalable and efficient business intelligence and IT Services
  • This role will report to Area Vice President of Business Operations

Location

 

  • USA, East Coast

 

Requirements

 

  • Bachelor’s degree in Business, Communications, Information Technology or equivalent.
  • 7-10 years of experience with tier 1 and 2 commercial business solutions such as Salesforce, Gainsight, Atlassian, Zendesk, Oracle, Marketo, NetSuite, Celigo, Clari, Dun & Bradstreet etc. 
  • Demonstrated leadership experience with security profiles and configuration, reports and dashboards, data integration tools and application integration
  • Proven ability to deliver implementation best practices and/or new processes and work with various groups to facilitate user adoption
  • Understanding of business platforms and business systems that made up business processes, with the ability to build and modify flows, custom views, and other content of intermediate complexity
  • Strong ability to critically evaluate information gathered from multiple sources, reconcile conflicts, decompose high-level information into details, abstract up from low-level information to a general understanding, and distinguish user requests from the underlying true needs
  • Strong ability to assess the impact of new requirements and connected applications, systems and processes
  • Ability to work independently as well as in a team environment.
  • Strong attention to detail and demonstrate exceptional ability to communicate verbally and in writing 
  • Strong ability to meet deadlines, handle and prioritize simultaneous requests, and manage laterally and upwards

 

Developer Relations Engineer
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

The CloudBees Community team is seeking a Developer Relations engineer.  In this role, you’ll own developer relations projects to increase developer adoption of Jenkins.  You’ll share ideas, foster community interactions, highlight effective software development practices, and inspire others to help the Jenkins project.  You will develop, test, and deliver crucial open source improvements.  You’ll interact with leading software engineers in our team and in the Jenkins community.  

You will be part of a team that is encouraging and assisting others as they adopt Jenkins.  You will strengthen and support the people, processes, infrastructure, and software in the Jenkins project.  You will interact with an international community of open source contributors both inside and outside of CloudBees.  Your work will be widely visible and deeply appreciated by users around the world.

What You’ll Do

  • Define and deliver projects that increase developer adoption of Jenkins
  • Improve the onboarding experience for new contributors to the Jenkins project by blog posts, writing documentation, and presenting online meetups
  • Lead outreach efforts to bring new developers into the Jenkins community
  • Mentor new participants in Jenkins development.  Use the results of those mentoring efforts to improve the developer experience for others
  • Document, describe, and present results both inside and outside CloudBees
  • Work closely with team members, the Jenkins community, the Continuous Delivery Foundation and other entities to identify and prioritize improvements and include those improvements in the Jenkins roadmap
  • Communicate effectively inside and outside CloudBees

What the Role Requires

  • Deep experience with Jenkins and its use in software development
  • Strong English language communications skills, both written and verbal
  • Java development skills for work in Jenkins core and Jenkins plugins
  • Willingness to learn rapidly and interact with others while learning
  • Strong attention to detail; ability to monitor, manage, and track work, and present data accurately to support decision making
  • Good organization and planning skills with the ability to anticipate needs and to determine the best use of time

Desired skills

  • Presentation, blogging, and advocacy experience
  • Hands-on experience with Docker, Kubernetes, or OpenShift and related container platform ecosystems.
  • Solid understanding of Amazon Web Services; Azure, Google Cloud
  • Release engineering or continuous delivery experience

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.

Front End Engineer
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 WILL BE PART OF

CloudBees Feature Management is a feature flag management solution used by engineering and product teams to mitigate release risk, improve developer productivity, and shorten user feedback loops.

Forward-looking enterprises use feature flags as a tool to expedite their continuous delivery and bring new innovation to market faster, with less risk. 

WHAT YOU’LL DO

  • Write quality code using Typescript, React and Jest
  • Own your code end to end. This means every aspect, starting from the design phase all the way through coding, building, deploying, and monitoring it after production
  • Work closely with product managers, designers, technical writers, and support engineers to ensure our user experience is as simple and frictionless as possible
  • Be mindful of security and privacy concerns and follow best practices.
  • Demonstrate flexibility by assisting with other projects when needed

WHAT THE ROLE REQUIRES

  • 2+ years experience  with React (including Hooks and Redux)
  • Solid knowledge of Javascript, Typescript and HTML/CSS
  • Solid Experience with JavaScript build tooling (e.g. WebPack and Babel)
  • Solid Experience with either Playwright, Cypress, Selenium or similar e2e testing framework
  • Experience with Bootstrap, React Bootstrap and good understanding of the internal workings of these specific or similar frameworks
  • Familiarity with Cloud Technologies such as GCP, AWS, Docker, Kubernetes and Helm preferred 
  • Familiarity with continuous delivery and continuous deployment practices 
  • Comfortable with working in a Agile environment with a high degree of autonomy and accountability
  • Strong desire to constantly learn new technologies with a general passion for improving developer productivity
  • Adaptability and a positive attitude

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
  • 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.

Verified by
Technical Evangelist
You may also like