I am newbie and poorly able to use git.
I somehow detached head from my git project repository, wrote many code and I tried to commit changes.
I used:
git add *
git commit -m "comment"
I tried to use git push, but I got
fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)
I am used git checkout master and changes was returned to master's branch commit, detached HEAD branch was deleted and I don't know how to return code which was lost.
(summing up the information in other answers)
Your commit is not lost, you can find it using git reflog :
# Here is a sample output :
# your commit should appear as 'HEAD@{xx}: commit: comment'
# ('comment' is the commit message you used)
$ git reflog
f9a32813c (HEAD -> master) HEAD@{0}: checkout: moving from 92e0cd0c6... to master
92e0cd0c6 HEAD@{1}: commit: comment
046a74ef8 (tag: foo) HEAD@{2}: checkout: moving from master to 046a74ef87ea...
Copy the hash you see at the beginning of the line (in the example above : 92e0cd0c6), and, from your current master branch, run :
git merge --ff-only 92e0cd0c6
For the command git checkout x where x is a commit, a tag, or anything that is not a short branch name, it leads to the detached HEAD. The detached HEAD is like a nameless branch. Once you switch to another branch or another detached HEAD, the previous one is gone and it makes people confused and think it's lost.
git checkout c8919ac48bc24080fa9d5c477bae8bcfb47991d4 # detached HEAD
git checkout master # switch to master, not detached
git checkout refs/heads/master # detached HEAD, though "master" and "refs/heads/master" are equivalent in most cases
git tag v1.0 c8919ac48bc24080fa9d5c477bae8bcfb47991d4
git checkout v1.0 # detached HEAD
git checkout origin/master # detached HEAD
Run git reflog and you can find the commit on which the detached HEAD was.
Then use git checkout <commit> to go back to the detached HEAD. A better practice is to run git checkout -b foo <commit> instead, to create a local branch foo from the commit so that the commit can be traced. This command is equal to git branch foo <commit> && git checkout foo.
If you actually intended to make the new commit on master, after you find the commit, you can cherry-pick it to master directly, git checkout master && git cherry-pick <commit>.
If you really want to push a detached HEAD to a branch, you need to specify the remote and the refspec instead of a bare git push.
git pull origin -r foo # before push, pull first to avoid non-fast-forward error
# -r is recommended to do a rebase pull
git push origin HEAD:foo # push the detached HEAD in the local repository to "foo" in "origin"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With