1

i have just do like this:

git checkout HEAD@{1} 

and it says I have changed to detached head state.

How can I do the same thing without changing to detached head state?

ziiweb
  • 28,757
  • 70
  • 168
  • 290
  • Possible duplicate of [git: switch branch without detaching head](http://stackoverflow.com/q/471300/456814). –  May 30 '14 at 05:30
  • Related: [Why did my Git repo enter a detached HEAD state?](http://stackoverflow.com/q/3965676/456814). –  May 30 '14 at 05:30
  • Related: [Fix a Git detached head?](http://stackoverflow.com/q/10228760/456814). –  May 30 '14 at 05:31

3 Answers3

2

If you're wanting to move the state of the current branch back to HEAD@{1} (potentially eliminating commits), then you'd want to use git reset --hard HEAD@{1} instead of git checkout.

Note that git reset --hard is a destructive operation.

If you're wanting to switch branches, then you should pass the name of the branch to git checkout (or use git checkout - to swap to whatever branch you were previously on before the current one).

Amber
  • 446,318
  • 77
  • 595
  • 531
  • Barely anything in git is actually destructive. And look out – he wrote `HEAD@{1}` – not `HEAD~1`. `HEAD@{1}` might actually point to a completely different branch. – Chronial Dec 24 '12 at 16:16
  • 1
    @Chronial `reset --hard` *is* actually destructive - it'll overwrite unstaged/uncommitted changes in the local filesystem without prompting, which is generally non-trivial to recover, if possible at all. – Amber Dec 24 '12 at 16:17
  • @Amber i never tried it but here it says it is possible. http://stackoverflow.com/questions/5473/undoing-a-git-reset-hard-head1 – ziiweb Dec 24 '12 at 23:59
  • @tirengarfio That's talking about something different - recovering the *commit*. I'm talking about losing changes that weren't yet committed. – Amber Dec 25 '12 at 00:08
  • @Amber fair point. As an experienced git user this seems obvious, but of course it’s not. So for any git beginner reading this: Be careful anything that’s commit will basically never be lost in git, but git has a few commands that will readily delete all your uncommited changes – `git reset --hard` is one of them. – Chronial Dec 25 '12 at 01:25
1

Think about what exactly you want to end up with. If you do not check out a branch, there can only be a detached head. I am assuming you want to move your branch back to its previous state – you can do that with this command:

git reset --hard HEAD@{1}

If you just want to check out the branch you had checked out before, this is what you’re looking for:

git checkout -
Chronial
  • 55,303
  • 13
  • 76
  • 85
0

Do you want to start a new branch? Just do:

git checkout -b new-branch-name HEAD@{1}
William Pursell
  • 174,418
  • 44
  • 247
  • 279