Sridhar Sarnobat
Sridhar Sarnobat

Reputation: 25286

git branch output without indent whitespace? (besides regex manipulation)

Is there a git branch option that will print all branches without the two spaces in front of the branch name? I thought --porcelain would be supported but apparently not for branch listing.

What I'm trying to do: I want to script deletion of merged branches without using low level regex manipulation like one would with awk, or in my case perl (so that my script is elegant and readable):

git branch | perl -pe 's{^\s*}{}g' | xargs -n 1 git branch -d

(Off topic, but for those who tend to hoard and hate deleting, this is a nice quick way to purge what you really don't need and keep a clean repo)

Upvotes: 4

Views: 1963

Answers (2)

Santhos
Santhos

Reputation: 3508

You can also use git branch directly. It probably uses for-each-ref internally.

To list the branches, use git branch --format "%(refname:short)". This does not output the *. Sample output:

develop
master
bug-123-fix-issue
task-345-do-stuff

To output the asterisk, use git branch --format "%(HEAD)%(refname:short)". Unfortunately, this creates a space in the beginning of all the other branches. Sample output:

*develop
 master
 bug-123-fix-issue
 task-345-do-stuff

However, you can play with the command anyway you want, so you can reverse it to have the asterisk at the end. It still contains the space, but at the end.

git branch --format "%(refname:short)%(HEAD)"

Sample output:

develop*
master
bug-123-fix-issue
task-345-do-stuff

Upvotes: 8

user4003407
user4003407

Reputation: 22132

You can use git for-each-ref to get some string for each matched reference in your repository:

git for-each-ref refs/heads --format "%(refname:short)"

or

git for-each-ref refs/heads --format "%(refname:strip=2)"

Upvotes: 3

Related Questions