Rican7
Rican7

Reputation: 1143

Git pull origin HEAD

I was taught that you could push to and pull from a remote branch matching the name of your current Git branch by doing:

git push origin HEAD

or

git pull origin HEAD

Its always worked for me before, but it strangely doesn't work sometimes, instead deferring to push/pulling from the master branch instead (which causes a merge on pull... not what I want to do). I know that you can easily push/pull from the branch you're on by simply using the name of the branch like:

git pull origin name-of-branch-i-want-to-pull-from

Anyway:

  1. Is there some reason that the HEAD is losing track/not pointing to my current branch, like it almost always does?
  2. Is there any way to push/pull to the branch that I'm currently working on (as long as the remote branch's name matches) without explicitly naming the branch in the command?

Upvotes: 31

Views: 54485

Answers (3)

zhengyue
zhengyue

Reputation: 1308

The thing is, when you do:

git push origin HEAD

HEAD here means the default branch on your local repository.

However, when you do:

git pull origin HEAD

HEAD here means the default branch on your remote repository.

These 2 HEADs can have the same branch name, but very often they are different.

For example, if the default branch of your local repository and remote repository are both master, then you switched to a new branch feature on local repository, then pushed it to remote by doing git push origin HEAD, the default branch on remote won't be changed to feature magically. Instead it will stay at master. At this point, if you do git pull origin HEAD on your feature branch, you are actually doing git pull origin master.

So I would suggest avoid doing git pull origin HEAD, because it's not obvious what's the default branch is on the remote, and can cause unexpected problems.

Upvotes: 12

Rican7
Rican7

Reputation: 1143

Thanks to some serious help by @abackstrom, I was able to fix my issue. Essentially, this post was my problem, and solution:

Git branch named origin/HEAD -> origin/master

The exact command to "recreate"/track a local HEAD branch/pointer correctly was:

git remote set-head origin -a

I hope this helps anyone else that runs into this issue.

Upvotes: 8

twalberg
twalberg

Reputation: 62379

HEAD is not really a branch. It's a pointer to the commit that you currently have checked out, and will often reference a branch, but if you do something like git checkout <sha> or git checkout <tag>, then HEAD references a commit directly, with no tie to a branch - this is called a "detached HEAD" state, and you should normally get a warning from git checkout when you enter such a state. In that state, trying to push/pull HEAD doesn't make sense, since you're not on a branch.

Upvotes: 6

Related Questions