Parsing the output of git branch
is not recommended, and not a good answer for future readers on Stack Overflow.
git branch
is what is known as a porcelain command. Porcelain commands are not designed to be machine parsed and the output may change between different versions of Git. git
branch
in a way that makes it difficult to parse (for instance, colorization). If a user has set color.branch
then you will get control codes in the output, this will lead to error: branch 'foo' not found.
if you attempt to pipe it into another command. You can bypass this with the --no-color
flag to git branch
, but who knows what other user configurations might break things.git branch
may do other things that are annoying to parse, like
put an asterisk next to the currently checked out branchThe maintainer of git has this to say about scripting around git branch
output
To find out what the current branch is, casual/careless users may have scripted around git branch, which is wrong. We actively discourage against use of any Porcelain command, including git branch, in scripts, because the output from the command is subject to change to help human consumption use case.
Answers that suggest manually editing files in the .git
directory (like .git/refs/heads) are similarly problematic (refs may be in .git/packed-refs instead, or Git may change their internal layout in the future).
Git provides the for-each-ref
command to retrieve a list of branches.
Git 2.7.X will introduce the --merged
option to so you could do something like the below to find and delete all branches merged into HEAD
for mergedBranch in $(git for-each-ref --format '%(refname:short)' --merged HEAD refs/heads/)
do
git branch -d ${mergedBranch}
done
Git 2.6.X and older, you will need to list all local branches and then test them individually to see if they have been merged (which will be significantly slower and slightly more complicated).
for branch in $(git for-each-ref --format '%(refname:short)' refs/heads/)
do
git merge-base --is-ancestor ${branch} HEAD && git branch -d ${branch}
done