TIL about scripting Git

I wanted to perform an action for each branch I have in Git

My initial inclination was to capture the output of git branch in order to enumerate the branches and then perform some operations on each in a for loop. But it turns out that has a couple of issues.

#!/bin/bash

for branch in $(git branch); do
    git_branch_cleanup.sh $branch
done

Not the least of which is that the output of git branch includes an asterisk next to your currently checked out branch which could cause issues depending on what operations you're going to perform. Sure you could do some fancy footwork in order to work around that, but it turns out that the recommended way of scripting git for this kind of situation is to to use for-each-ref

#!/bin/bash

for branch in $(git for-each-ref --format='%(refname:short)' refs/heads); do
    git_branch_cleanup.sh $branch;
done

Information about this command and more can be found here.