Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git list of remote branches

I'm looking for the best way to execute a function for each Git remote branch in a PowerShell script.

I don't know the best way to get a list of Git remote branches. I can successfully list all remote branches, but I always end up with pesky formatting in the branch names.

Here are the commands I've tried and the resulting arrays I've gotten.

$allBranches = git branch -r
$allBranches = @('  origin/branch1', '  origin/branch2', '  origin/branch3')

$allBranches = git for-each-ref --shell --format=%(refname) refs/remotes/origin
$allBranches = @(''origin/branch1'', ''origin/branch2'', ''origin/branch3'')

I would like $allBranches = @('origin/branch1', 'origin/branch2', 'origin/branch3'), so my current approach is to just manually remove formatting from the weird branch names using Trim():

foreach($branch in $allBranches) {
    # Format $branch
    # Do function
}

Is there a better approach?

like image 544
Elaine Lin Avatar asked Aug 07 '15 15:08

Elaine Lin


People also ask

How do I check out a remote branch?

In order to checkout a remote branch you have to first fetch the contents of the branch. In modern versions of Git, you can then checkout the remote branch like a local branch. Older versions of Git require the creation of a new branch based on the remote .

What is name of remote branch in git?

While “master” is the default name for a starting branch when you run git init which is the only reason it's widely used, “origin” is the default name for a remote when you run git clone . If you run git clone -o booyah instead, then you will have booyah/master as your default remote branch.

What command will download remote branches?

Fetch command will retrieve all changes from the remote branch which do not exist in the local branch. FETCH_HEAD ref track can be used for fetched changes from remote branches.


2 Answers

The Trim() operation should do what you want.

$allTrimmedBranches = @()
foreach($branch in $allBranches) {
    $allTrimmedBranches += $branch.Trim()
}
#do function
like image 185
weirdev Avatar answered Oct 25 '22 19:10

weirdev


$branches = git for-each-ref --format='%(refname:short)' refs/remotes/origin

like image 34
dimiboi Avatar answered Oct 25 '22 20:10

dimiboi