1

I want to write a bash script that scans the branches in my repository, checkout them one by one and fix a typo in every source using sed.

My problem is to make a list of the branches with origin/HEAD filtered out.

branches=$(git branch -r | grep 'origin/^(HEAD)+')

Code inspired by this answer: Regex - Does not contain certain Characters

But I got an empty list in $branches.

Zack
  • 119
  • 2
  • 13
  • 1
    The caret operator only means inverse for a character class like `[^a-z]`, not for parentheses. Maybe you want the `grep -v ` flag? – xdhmoore Nov 08 '20 at 02:33
  • Also, just a hunch, but if you are trying to automate the application of a change across a bunch of branches, you might look at `git cherry-pick` or `git apply`. It might easier to apply a single commit or diff that way instead of sed'ing and committing repeatedly in a script. – xdhmoore Nov 08 '20 at 02:36
  • On the off-chance your `git branch -r` isn't returning all the branches you need, there's a SO [thread on that](https://stackoverflow.com/questions/3471827/how-do-i-list-all-remote-branches-in-git-1-7/3472296). – xdhmoore Nov 08 '20 at 02:42
  • @xdhmoore, git branch -r dose indeed return all of my branches. The problem is when iterating over $branches I get the values "origin/HEAD" and "->". I dont want to apply git checkout on those, so was hoping to filter it out using grep. – Zack Nov 08 '20 at 02:49
  • @xdmoore, thanks for pointing out git apply and cherry-pick. Im gonna read more about those, see how can I use them. – Zack Nov 08 '20 at 02:51
  • 2
    This would exclude `origin/HEAD` using `git branch -r | grep -vF origin/HEAD`. But you should not assign a list to a string variable. Use an array instead. See: [my answer](https://stackoverflow.com/a/64734414/7939871). – Léa Gris Nov 08 '20 at 03:09

1 Answers1

3

Get git remote branches into a Bash array:

read -r -d '' -a branches < <(
  git \
    branch \
    --list \
    --remotes \
    --format '%(refname:lstrip=-1)' |
      grep -vF HEAD
)
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
  • Indeed, I tried branches=$(git branch -r | grep -vF 'HEAD') to see it kinda did the trick the short way. The read command on the other hand results in a 'Syntax error: "(" unexpected'. Another puzzle for me to solve... – Zack Nov 08 '20 at 03:23
  • @Zack this is Bash code, so it will fail with zsh or ksh – Léa Gris Nov 08 '20 at 03:35
  • finally solved. needed to call "bash my_script.sh" instead of "sh my_script.sh". And they said Ubuntu is user friendly... – Zack Nov 08 '20 at 04:52