How to fetch all Git branches

后端 未结 30 1438
情书的邮戳
情书的邮戳 2020-11-22 09:38

I cloned a Git repository, which contains about five branches. However, when I do git branch I only see one of them:

$ git branch
* master
         


        
30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 10:08

    How to Fetch All Git Branches Tracking Single Remote.

    This has been tested and functions on Red Hat and Git Bash on Windows 10.


    TLDR:

    for branch in `git branch -r|grep -v ' -> '|cut -d"/" -f2`; do git checkout $branch; git fetch; done;
    

    Explanation:

    The one liner checks out and then fetches all branches except HEAD.

    List the remote-tracking branches.

    git branch -r
    

    Ignore HEAD.

    grep -v ' -> '
    

    Take branch name off of remote(s).

    cut -d"/" -f2
    

    Checkout all branches tracking a single remote.

    git checkout $branch
    

    Fetch for checked out branch.

    git fetch
    

    Technically the fetch is not needed for new local branches.

    This may be used to either fetch or pull branches that are both new and have changes in remote(s).

    Just make sure that you only pull if you are ready to merge.


    Test Setup

    Check out a repository with SSH URL.

    git clone git@repository.git
    

    Before

    Check branches in local.

    $ git branch
    * master
    

    Execute Commands

    Execute the one liner.

    for branch in `git branch -r|grep -v ' -> '|cut -d"/" -f2`; do git checkout $branch; git fetch; done;
    

    After

    Check local branches include remote(s) branches.

    $ git branch
      cicd
      master
    * preprod
    

提交回复
热议问题