How can I interface the GitHub CLI with "git branch -d"?

I file pull requests to an upstream repo which I’m not a maintainer of. I want to delete my local and remote branches from which I filed those PRs and which have been merged/closed. I want to do this in one swoop from the terminal.

I use the GitHub CLI to check which of my branches have been merged/closed, for example, with gh pr list -A <author> -s merged

I also know that I can pipe results into xargs git branch -d to delete branches.

But what I don’t know is how to filter the original results so that the piping succeeds.

Here’s an example of one such result:

#6876 fixed typo/grammar, improved diction author:patch-33

How can I pipe just the acceptable content and remove what isn’t? Can anyone help me with this?

gh pr list --json 'headRefName' --state merged|
  jq -r '.[].headRefName'
1 Like

Or something like that, you’ll need to look at the json fields and decide what you care about.

And keep in mind that it’s possible you’ve locally deleted a branch or replaced it w/ something else.


If I run gh pr list -A ConsciousClay -s merged --json 'headRefName' | jq -r '.[].headRefName', then I get a list of branch names.

If I run git branch -l, then again I see a list of branch names.

But when I pass the results of the first command into xargs git branch -d, I receive error messages saying that the names of the branches aren’t found. But the branches are there and those are their names. If I manually enter the branch name into git branch -d, it has no problem deleting it.

For example, here’s one result from the first command:

And here’s one results from the second command:

Piping the results of the first command into xargs git branch -d tells me:
error: branch ‘patch-47?’ not found.

Any ideas? Is it because for some reason a question mark is being added? I should add I tried from Powershell and Mingw64.

Sounds like a line ending thing?

You could just use xargs echo and then run the command later…