I was doing some work in my repository and noticed a file had local changes. I didn\'t want them anymore so I deleted the file, thinking I can just checkout a fresh copy. I
HEAD is a pointer, and it points — directly or indirectly — to a particular commit:
Attached HEAD means that it is attached to some branch (i.e. it points to a branch).
Detached HEAD means that it is not attached to any branch, i.e. it points directly to some commit.
In other words:
To better understand situations with attached / detached HEAD, let's show the steps leading to the quadruplet of pictures above.
We begin with the same state of the repository (pictures in all quadrants are the same):
Now we want to perform git checkout
— with different targets in the individual pictures (commands on top of them are dimmed to emphasize that we are only going to apply those commands):
This is the situation after performing those commands:
As you can see, the HEAD points to the target of the git checkout
command — to a branch (first 3 images of the quadruplet), or (directly) to a commit (the last image of the quadruplet).
The content of the working directory is changed, too, to be in accordance with the appropriate commit (snapshot), i.e. with the commit pointed (directly or indirectly) by the HEAD.
So now we are in the same situation as in the start of this answer:
I wanted to keep my changes so, I just fix this doing...
git add .
git commit -m "Title" -m "Description"
(so i have a commit now example: 123abc)
git checkout YOURCURRENTBRANCH
git merge 123abc
git push TOYOURCURRENTBRANCH
that work for me
Addendum
If the branch to which you wish to return was the last checkout that you had made, you can simply use checkout @{-1}
. This will take you back to your previous checkout.
Further, you can alias this command with, for example, git global --config alias.prev
so that you just need to type git prev
to toggle back to the previous checkout.
Detached head means you are no longer on a branch, you have checked out a single commit in the history (in this case the commit previous to HEAD, i.e. HEAD^).
You only need to checkout the branch you were on, e.g.
git checkout master
Next time you have changed a file and want to restore it to the state it is in the index, don't delete the file first, just do
git checkout -- path/to/foo
This will restore the file foo to the state it is in the index.
git branch tmp
- this will save your changes in a new branch called tmp
.git checkout master
master
, run git merge tmp
from the master
branch. You should be on the master
branch after running git checkout master
.If you have changed files you don't want to lose, you can push them. I have committed them in the detached mode and after that you can move to a temporary branch to integrate later in master.
git commit -m "....."
git branch my-temporary-work
git checkout master
git merge my-temporary-work
Extracted from:
What to do with commit made in a detached head