Home > OS >  Bash - how to get a list of git branches?
Bash - how to get a list of git branches?

Time:08-27

I am working on a bash script that searches for git branches and lists them out:

# Search for a branch by name.
gbs () {
  branches=`git branch --list $1*`
  branches_len=${#branches[@]}
  echo "$branches_len branches found:"
  for branch in $branches
  do
   printf "$branch\n"
  done
}

The output is:

joe.bloggs$ gbs X
1 branches found:
XX/test1
XX/test2

Why is it just showing 1 branch found, when it is iterating the array and finding 2 branches?

CodePudding user response:

The git branch command is meant for interactive shell purpose only. It has fancy formatting, layout and highlights, that makes it easier to read for a human-being; but it turns into a bug-trap, as soon as one tries to parses it from a script.

Because it does not provide a consistent stable and programmatically friendly output format; it cannot be relied upon, for parsing its output with a shell script.

The common and stable Git API entry point for most shell scripting needs, is the git for-each-ref command.

So! Here your branch search function can be simplified, and made significantly more reliable using git for-each-ref rather than git branch:

gbs() {
  git for-each-ref --format='%(refname:strip=2)' "refs/heads/$1"
}

Or if you want to search for all patterns provided as arguments:

gbs() {
  git for-each-ref --format='%(refname:strip=2)' "${@/#/refs\/heads\/}"
}

For nice and portable bash/zsh git boilerplate functions examples, with mostly the same branch search function for bash completion that what I wrote above for you; see: https://github.com/git/git/tree/master/contrib/completion

CodePudding user response:

Ok, I just found the correct syntax:

# Search for a branch by name.
gbs () {
  branches=(`git branch --list $1*`)
  branches_len=${#branches[@]}
  echo "$branches_len branches found:"
  for branch in ${branches[@]}
  do
   printf "$branch\n"
  done
}
  • Related