2

I did not realize I've been working on a detached HEAD (a32b42b123) branch until now. This branch is falling behind master a lot. I did the following operations, git checkout master && git pull origin master git checkout a32b42b123 && git rebase master to sync up this branch with master and noticed most of the changes I made in this branch are gone. Now I understand what a detached HEAD is. But how could I perform the git rebase master safety here without wiping out the change I made?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
user2372074
  • 781
  • 3
  • 7
  • 18

1 Answers1

2

Commits in Git are immutable. If you started off at a32b42b123 and made changes, the tip of your branch would no longer be a32b42b123, but a different commit. When you checkout back to that commit, as you've seen, you lose the changes you've made on top of it.

You could, of course, use detached head, but that's just making live difficult for no (good) reason, especially when branches are so cheap. Just create a named branch from that commit and make your changes there:

$ git checkout a32b42b123 -b mybranch 
# make some changes, commit
$ git fetch origin
$ git rebase origin/master
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • but doing this rebase will lose the previous change I made on a32b42b123, right? – user2372074 Nov 21 '18 at 17:29
  • @user2372074 Commits are read-only. You cannot change `a32b42b123` once its created - you can make changes in the branch, and rebasing the branch will retain them (assuming no merge conflicts, of course!) – Mureinik Nov 21 '18 at 17:33
  • Thanks for the reply, after rebasing, all the changes are gone. – user2372074 Nov 22 '18 at 02:34
  • Thanks, I did git checkout master && git pull origin master git checkout a32b42b123 && git rebase master' @user2372074 – user2372074 Nov 28 '18 at 18:47