Reputation: 399
I have deleted branch on which I was rebased. I was thinking that solution might be to checkout to master and then to fetch remote branch and continue with work, but I get this error,
notice: HEAD points to an unborn branch
How to fix this?
Upvotes: 2
Views: 109
Reputation: 1267
Yes, you should be able to do git reflog and find the SHA1 for the commit at the tip of your deleted branch, then just git checkout [sha]. And once you're at that commit, you can just git checkout -b [branchname] to recreate the branch from there.
You can do it in one step:
git checkout -b <branch> <sha>
This is creating a new branch for that SHA1 with the name which you give.
Upvotes: 0
Reputation: 487755
Git normally will not allow you to delete the branch you're on, for just this sort of reason.
The most fundamental problem here is that the branch name contained the commit hash ID. That is, according to your comment, you did this:
git checkout feature/branch_1
which put the name feature/branch_1
into the special name HEAD
. The name itself, i.e., feature/branch_1
, contained the 40-character hash ID of the branch tip, so that the name remembered the actual commit hash.
Then you ran:
git branch -d feature/branch_1
Git should have just said no, you may not do that. (There have been some bugs around this when using git worktree add
, and there are various ways you can cause yourself problems, but git branch
itself is supposed to just say no here.) When this succeeded, you were left with:
HEAD
contains feature/branch_1
feature/branch_1
does not exist.The way to fix it is to re-create the name feature/branch_1
while putting the correct commit hash ID into it. The problem is that there is no memory of which commit hash it should be holding: that hash ID was stored under the name feature/branch_1
, and no longer is.
What you need, then, is some alternative method for finding this hash ID. One way is that if there is another name that also stores the correct hash ID, you can read the hash ID from that other name:
git branch feature/branch_1 origin/feature/branch_1
for instance. However, if there is no such other name, that won't work.
Fortunately, HEAD
has a reflog, and the HEAD
reflog stores the raw commit hashes of the commits you have visited. Unfortunately, in this state it looks like Git refuses to use it:
$ git reflog HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
and:
$ git rev-parse HEAD@{0}
HEAD@{0}
fatal: ambiguous argument 'HEAD@{0}': unknown revision or path not in the working tree.
However, this does the trick:
$ tail -1 .git/logs/HEAD | awk '{print $2}'
b5101f929789889c2e536d915698f58d5c5c6b7a
so you can resort to this particular trick in this particular case (which should otherwise never occur anyway).
Upvotes: 3