Iterate over branches in your git repository

Sometimes when we try to automate tasks, there is a need to iterate over branches or tags in a repository. Hardcoding branch names is a no-go because we want our scripts to be reusable. The first thing I do in such a case is checking the git branch command output.

No input cannot be parsed with sophisticated enough regular expression or long enough chain of piped cut, tr, etc., but I want to keep my scripts simple. I want anyone to understand it at first glance. If possible – without head-scratching while looking at regular expressions or piped statements.

That can be done. git for-each-ref is a way to go. I describe it as a more powerful git branch --list.

It’s more verbose, and we get a list of all refs, not only local branches but also remote branches and tags. That output can be limited with the pattern refs which need to match.

We’re only interested in the ref name, so I define an output format.

Much better, this could already be used in a for loop of any shell script. We could, however, generate the script with the --format option. --shell, --perl, --python, --tcl will handle language-specific quoting for us.

Let’s check how many bytes README.md file has on each branch.

This output can be directly eval-ed:

It’s not a command you will use every day, but it will save you a lot of work when you need it.

Have you heard about GitHub deprecating short SHA when referencing actions in workflows?

I’m maintaining many workflows in our organization, and we used to be practicing short SHA to reference some 3rd party actions. Lately, I had to go over all workflow YAML files on every branch, in every repository I work with to check if it uses short SHA, and update it if needed. I used grep instead of wc and executed git for-each-ref on each repository I maintain.

I can’t imagine how much work it would take to iterate over repositories and branches manually. It’s much more pleasant to just scroll over a list.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published.