Search code examples
gitversion-control

Git Fetch vs Git Fetch Origin


I wanted to fetch a single remote branch and then rebase my current working branch against that as I am sharing it with someone. Usually I would just do:

git fetch

git rebase origin/branch_im_working_on

That seems to work ok but it appears to fetch all branches from the remote repository. So I looked around and found this:

git fetch origin branch_im_working_on

When I do this git tells me it fetched HEAD and then try to do:

git rebase origin/branch_im_working_on

git tells me that I am up to date and there is nothing to do even though I know there are changes pushed to remote.

If I try to do:

git rebase origin branch_im_working_on

I get a lot of merge conflicts so had to resort back to the original commands to get my branch up to date:

git fetch

git rebase origin\branch_im_working_on

Can someone help me understand what is happening here?


Solution

  • Differences between git fetch and git fetch origin

    • If the git repo only has one remote, origin (you can check remotes by git remote -v), the two commands work the same.
    • If the git repo contains more than one remote, such as origin and upstream. git fetch will fetch all the changes from both remotes. git fetch origin will only fetch the changes from the remote origin.

    Besides, if you only want to fetch a certain branch from a remote, you can use git fetch remotename branchname. For example, git fetch origin branch_im_working_on will only fetch the changes from the origin remote for the branch_im_working_on branch.

    Rebase your local changes on the top on the remote branch:

    Assume the commit history looks as below after fetching:

    …---A---B---C---D  branch_im_working_on
             \
              E---F   origin/branch_im_working_on
    

    If you want your local changes (commit C and commit D) on top of the origin/branch_im_working_on (latest commit), any one of the below commands can work:

    git rebase origin branch_im_working_on
    git rebase origin/branch_im_working_on
    git fetch origin branch_im_working_on --rebase
    

    Then the commit history will be:

    …---A---B---E---F---C---D  branch_im_working_on
                    |
         origin/branch_im_working_on
    

    But the command git rebase origin\branch_im_working_on will not work (for Windows OS) since origin\branch_im_working_on is not a valid branch (neither local branch nor tracking branch).