How can I iterate through all the local branches in my repository using bash script. I need to iterate and check is there any difference between the branch and some remote branches. Ex

for branch in $(git branch); 
do
    git log --oneline $branch ^remotes/origin/master;
done

I need to do something like given above, but the issue I'm facing is $(git branch) gives me the folders inside the repository folder along with the branches present in the repository.

Is this the correct way to solve this issue? Or is there another way to do it?

Thank you

share|improve this question
    
Possible duplicate of for loop over all git branches with certain name – pihentagy Aug 24 '16 at 12:19
up vote 116 down vote accepted

You should not use git branch when writing scripts. Git provides a “plumbing” interface that is explicitly designed for use in scripting (many current and historical implementations of normal Git commands (add, checkout, merge, etc.) use this same interface).

The plumbing command you want is git for-each-ref:

git for-each-ref --shell \
  --format='git log --oneline %(refname) ^origin/master' \
  refs/heads/

Note: You do not need the remotes/ prefix on the remote ref unless you have other refs that cause origin/master to match multiple places in the ref name search path (see “A symbolic ref name. …” in the Specifying Revisions section of git-rev-parse(1)). If you are trying to explictly avoid ambiguity, then go with the full ref name: refs/remotes/origin/master.

You will get output like this:

git log --oneline 'refs/heads/master' ^origin/master
git log --oneline 'refs/heads/other' ^origin/master
git log --oneline 'refs/heads/pu' ^origin/master

You can pipe this output into sh.

If you do not like the idea of generating the shell code, you could give up a bit of robustness* and do this:

for branch in $(git for-each-ref --format='%(refname)' refs/heads/); do
    git log --oneline "$branch" ^origin/master
done

* Ref names should be safe from the shell’s word splitting (see git-check-ref-format(1)). Personally I would stick with the former version (generated shell code); I am more confident that nothing inappropriate can happen with it.

Since you specified bash and it supports arrays, you could maintain safety and still avoid generating the guts of your loop:

branches=()
eval "$(git for-each-ref --shell --format='branches+=(%(refname))' refs/heads/)"
for branch in "${branches[@]}"; do
    # …
done

You could do something similar with $@ if you are not using a shell that supports arrays (set -- to initialize and set -- "$@" %(refname) to add elements).

share|improve this answer
19  
Seriously. There isn't a simpler way to do this? – Jim Fell Apr 17 '15 at 21:59
3  
But what if I want to use one of the filtering options of git branch, like --merged, would I have to duplicate the logic in git branch? There has to be a better way to do this. – Thayne Apr 20 '15 at 21:23
    
Simplier version: git for-each-ref refs/heads | cut -d/ -f3- – wid Jan 13 '16 at 14:47
3  
@wid: Or, simply, git for-each-ref refs/heads --format='%(refname)' – John Gietzen May 4 '16 at 19:30
    
If the output is safe from newlines, one can do this: git for-each-ref --format='%(refname)' refs/heads | while read x ; do echo === $x === ; done. Note that this puts the while loop into a subshell. If you want the while loop in the current shell, then this: while read x ; do echo === $x === ; done < <( git for-each-ref --format='%(refname)' refs/heads ) – Chris Cogdon Oct 23 '17 at 22:26

This is because git branch marks the current branch with an asterisk, e.g.:

$ git branch
* master
  mybranch
$ 

so $(git branch) expands to e.g. * master mybranch, and then the * expands to the list of files in the current directory.

I don't see an obvious option for not printing the asterisk in the first place; but you could chop it off:

$(git branch | cut -c 3-)
share|improve this answer
3  
If you surround in double-quotes you can stop bash from expanding the asterisk - though you'll still want to remove it from the output. A more robust way of removing an asterisk from any point would be $(git branch | sed -e s/\\*//g). – Nick Oct 2 '10 at 16:00
2  
nice, i really like your 3- solution. – Andrei Petre May 10 '13 at 10:28
    
Slightly simpler sed version: $(git branch | sed 's/^..//') – jdg Feb 8 '15 at 18:17
4  
slightly simpler tr version: $(git branch | tr -d " *") – ccpizza Apr 15 '15 at 15:50
    
This solution removes the * stackoverflow.com/a/12142066/977566 – LJT Dec 18 '16 at 23:31

I would suggest $(git branch|grep -o "[0-9A-Za-z]\+") if your local branches are named by digits, a-z, and/or A-Z letters only

share|improve this answer

I iterate as it for example :

for BRANCH in `git branch --list|sed 's/\*//g'`;
  do 
    git checkout $BRANCH
    git fetch
    git branch --set-upstream-to=origin/$BRANCH $BRANCH
  done
git checkout master;
share|improve this answer

The accepted answer is correct and really should be the approach used, but solving the problem in bash is a great exercise in understanding how shells work. The trick to doing this using bash without performing additional text manipulation, is to ensure the output of git branch never gets expanded as part of a command to be executed by the shell. This prevents the asterisk from ever being expanding in the file name expansion (step 8) of shell expansion (see http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html)

Use the bash while construct with a read command to chop the git branch output into lines. The '*' will be read in as a literal character. Use a case statement to match it, paying special attention to the matching patterns.

git branch | while read line ; do                                                                                                        
    case $line in
        \*\ *) branch=${line#\*\ } ;;  # match the current branch
        *) branch=$line ;;             # match all the other branches
    esac
    git log --oneline $branch ^remotes/origin/master
done

The asterisks in both the bash case construct and in the parameter substitution need to be escaped with backslashes to prevent the shell interpreting them as pattern matching characters. The spaces are also escaped (to prevent tokenization) because you are literally matching '* '.

share|improve this answer

Extending on from @finn's answer (thank you!), the following will let you iterate over the branches without creating an intervening shell script. It's robust enough, as long as there's no newlines in the branch name :)

git for-each-ref --format='%(refname)' refs/heads  | while read x ; do echo === $x === ; done

The while loop runs in a subshell, which is usually fine unless you're setting shell variables that you want to access in the current shell. In that case you use process substitution to reverse the pipe:

while read x ; do echo === $x === ; done < <( git for-each-ref --format='%(refname)' refs/heads )
share|improve this answer

Easiest option to remember in my opinion:

git branch | grep "[^* ]+" -Eo

Output:

bamboo
develop
master

Grep's -o option (--only-matching) restricts the output to only the matching parts of the input.

Since neither space nor * are valid in Git branch names, this returns the list of branches without the extra characters.

Edit: If you're in 'detached head' state, you'll need to filter out the current entry:

git branch --list | grep -v "HEAD detached" | grep "[^* ]+" -oE

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.