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
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.
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
The Bash for
loop wasn't working for me, but this did exactly what I wanted. All the branches from my origin mirrored as the same name locally.
git checkout --detach
git fetch origin '+refs/heads/*:refs/heads/*'
See Mike DuPont's comment below. I think I was trying to do this on a Jenkins Server which leaves it in detached head mode.
If you are here seeking a solution to get all branches and then migrate everything to another Git server, I put together the below process. If you just want to get all the branches updated locally, stop at the first empty line.
git clone <ORIGINAL_ORIGIN>
git branch -r | awk -F'origin/' '!/HEAD|master/{print $2 " " $1"origin/"$2}' | xargs -L 1 git branch -f --track
git fetch --all --prune --tags
git pull --all
git remote set-url origin <NEW_ORIGIN>
git pull
<resolve_any_merge_conflicts>
git push --all
git push --tags
<check_NEW_ORIGIN_to_ensure_it_matches_ORIGINAL_ORIGIN>
I usually use nothing else but commands like this:
git fetch origin
git checkout --track origin/remote-branch
A little shorter version:
git fetch origin
git checkout -t origin/remote-branch
Looping didn't seem to work for me and I wanted to ignore origin/master. Here's what worked for me.
git branch -r | grep -v HEAD | awk -F'/' '{print $2 " " $1"/"$2}' | xargs -L 1 git branch -f --track
After that:
git fetch --all
git pull --all
Set alias: (based on the top answer)
git config --global alias.track-all-branches '!git fetch --all && for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done && git fetch --all'
Now to track all the branches:
git track-all-branches