Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid detached headstate in git?

Tags:

git

I am trying to get a remote branch and track it but when I do:

git checkout remotes/mybranch

When I do git branch -a it displays remotes/mybranch in the red color? I get an error:

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

How can I checkout to this mybranch locally and track it? How can I avoid the detached HEAD state?

like image 796
Pindakaas Avatar asked Jul 23 '15 01:07

Pindakaas


1 Answers

what do I do next time to avoid this detached state?

See "Why did my Git repo enter a detached HEAD state?"

You simply have to checkout a local named branched, as opposed to a remote tracking one (like origin/mybranch).
The remote tracking branch origin/mybranch isn't made to record commits, but only to track the commits fetched from the upstream repo.

To avoid that:

git checkout -b abranch origin/abranch 

Or rather, since Git 2.23 (Q3 2019), using git switch:

git switch abranch

That will will create the local branch "abranch" and track origin/abranch.

See "Difference between git checkout --track origin/branch and git checkout -b branch origin/branch"

like image 59
VonC Avatar answered Oct 22 '22 02:10

VonC