Git create branch where detached HEAD is
Asked Answered
Q

2

156

I tried something like this:

git branch temp

to create a new branch but don't move the HEAD. But I get:

# Not currently on any branch.

I don't want to merge anything, I just want a new branch at the current HEAD.

Quinacrine answered 12/3, 2014 at 23:29 Comment(0)
O
277

You're sitting on a detached HEAD:

git checkout <sha>

You want to make a branch at that commit:

git branch my-new-branch

And now switch to that branch:

git checkout my-new-branch
Obnoxious answered 12/3, 2014 at 23:39 Comment(3)
Yes, but slightly simpler is git checkout -b my-new-branch.Sensitize
@Sensitize Yeah, that shorthand is quicker. I broke it into separate pieces because it looked like the OP was expecting branch to not only make the branch, but switch to it too. I wanted to make clear the difference between branch and checkout.Obnoxious
That shorthand is quicker to type, but slower to remember. I like the solution given.Chatoyant
E
11

You can also use:

git switch -c <new branch name>
Exocarp answered 15/1, 2022 at 9:30 Comment(2)
With modern Git, this should be the accepted answer.Marmoset
@Marmoset as of git version 2.44.0 (2024-02-23) the documentation still says "THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE." so maybe it should not be the accepted answer yet.Solidary

© 2022 - 2024 — McMap. All rights reserved.