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 [email protected]
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
--single-branch
setting when cloning: stackoverflow.com/questions/17714159/… (git fetch --all
will never work if you've specified only one branch!) – Matthew Wilcoxsongit clone --bare <repo url> .git
(notice you need to add "--bare" and ".git" at the end to clone the repo as a "bare" repo), thengit config --bool core.bare false
(sets the "bare" flag to false), thengit reset --hard
(moves the HEAD to current HEAD on the repo). Now if yougit branch
you should see all branches from the repo you cloned. – Gabriel Ferraz