Red Green Repeat Adventures of a Spec Driven Junkie

How to Push a detached git HEAD

Today’s article covers a quick method of committing to remote branches while in a detached HEAD state.

Requirements

If you would like to follow along these are the things you need:

  • a forked github repository, you can fork any of my repositories
  • a local copy of the repository, for example, my emacs configuration:
    • $ git clone https://github.com/a-leung/rails_api

detached HEAD ???

It is a state when the current git branch does not have an explicit reference to a branch.

To get into a detached state, just checkout the equivalent remote branch like so:

$ git checkout remotes/origin/master
Note: checking out 'remotes/origin/master'.

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 performing another checkout.

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

  git checkout -b <new-branch-name>

HEAD is now at 75ebcbf... initial commit

In this state, one can work as if the repository was tracked, but it’s not since this message will always appear.

$ git status
HEAD detached from origin/master

no changes added to commit (use "git add" and/or "git commit -a")

Up to now, I always thought I had to make a full branch before being able to push changes to the remote.

Surprise, Surprise

I learned that the current detached HEAD can be pushed by the following command:

git push <remote name> HEAD:<remote branch name>

In one case, it can be:

git push origin HEAD:master

If one wanted to write new commits directly to the remote master branch without having local changes!

I too like to live dangerously

This basically means HEAD is the current branch and is a reference that can be used the same as a branch. Neat!

Normally, I would recommend against such practices, but there may be circumstances that having this knowledge would be useful.