Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`git branch --list` returns files?

This is strange. I'm trying to make a script that will checkout every local branch and rebase origin/master onto it.

So this is my script:

for br in `git branch -l`; do
    git checkout $br
    git rebase origin/master
done

Simple. But before I made the script, I wanted to make sure that `git branch -l` returns what I think it is returning.....it isn't.

git branch -l returns the correct result. But `git branch -l` is actually returning all local branch PLUS the files in the current dir!

It returns it like this:

[list of local branches minus master] [list of files in the current dir] master

`git branch --list` behaves the same way.

Why is this happening?

And is there a better way to rebase origin/master to all local branches?

like image 449
Nacht Avatar asked Jul 03 '13 15:07

Nacht


2 Answers

This is kind of a silly thing.

git branch --list is putting an asterisk in front of the currently selected branch; your shell script is interpreting that as the wildcard and adding the files in the current directory to the list of items to traverse with your for loop.

You can try

for br in `git branch -l | tr '*' ' '`; do
    git checkout $br
    git rebase origin/master
done
like image 172
antlersoft Avatar answered Oct 08 '22 05:10

antlersoft


The other thing you can do, not really needed here but useful for more robust scripts as it were, is to use git for-each-ref to extract the refnames you want. For instance, the equivalent of git branch --list minus the prefix white-space-or-asterisk is:

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

as in this example:

$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
$ git for-each-ref refs/heads/ --format='%(refname:short)'
master

Likewise you can get remotes (git branch -r) by using refs/remotes/ instead of refs/heads/, and you can find tags using refs/tags/. There are even extra options with for-each-ref designed to protect strings from various program actions (not needed for this particular case, see the documentation for git check-ref-format and its restrictions on branch names), but which make it possible to use eval on the output of git for-each-ref.

like image 41
torek Avatar answered Oct 08 '22 05:10

torek