Bostonian
Bostonian

Reputation: 687

How to fixed the detached head in Git

I have two remote repositories (let's call them remote1 and remote2) and both of them has a branch called "mainline".

When I try to checkout the "mainline" from remote1, I use "git checkout remote1/mainline" since if I just "git checkout mainline", git would complain since both remote1 and remote2 have "mainline". But now I got into the so called detached HEAD mode and I already made one git commit under detached HEAD mode.

In git's world, I know I should work on branch, so is there any way I could fix the detached HEAD mode and work on a normal branch mode? (I hope the commit I already made could still remain).

Another question is that if I have two repositories, both of them have a branch with same name, what is the recommended way to checkout this branch from a specific remote without going to the detached HEAD mode?

Upvotes: 0

Views: 157

Answers (2)

plugwash
plugwash

Reputation: 10494

Generally you work with upstream branches through a local branch which tracks a "remote tracking branch". The remote tracking branch appears when you set up and fetch from the remote.

In the easy case git automatically creates the local branch and sets it up to track the remote tracking branch when you try to check out a branch name that doesn't exist locally but does exist remotely, however sometimes you have to do it manually because of ambiguities.

In git's world, I know I should work on branch, so is there any way I could fix the detached HEAD mode and work on a normal branch mode? (I hope the commit I already made could still remain).

Note down the id of the commit you just made, then.

git checkout -b remote1mainline remote1/mainline
git merge <commit id>

You will now have a branch "remote1mainline" tracking remote1/mainline, and you can commit, push and pull as normal.

Edit: fixed terminology.

Upvotes: 1

eftshift0
eftshift0

Reputation: 30156

To get you out of your current situation without losing the work you already committed, simply checking out a new branch would suffice:

git checkout -b new-branch

Now you have a local branch new-branch. It's not tracking any other branch, by the way. If you would like to have this branch associated to one of the remote branches, you can do it by using git branch --set-upstream

git branch --set-upstream remote1/mainline

Having two remotes with the same branch on them should not be much pain.... other than having to provide one remote for some commands.... like to create a new local branch mainline from one of the two remote branches, you will have to specify which remote branch to use:

git checkout -b mainline remote2/mainline

That was not that painful, was it?

Upvotes: 3

Related Questions