DEV Community

Shinji NAKAMATSU
Shinji NAKAMATSU

Posted on

Alias to remove deleted branches in a git remote at once

When working with git, local branches that have already been used are accumulated. Then I want to delete them all at once, so I defined an alias.

git config --global alias.prune-no-longer-exist '!git branch -vv | grep '"'"': gone]'"'"' | grep -v '"'"'\*'"'"' | awk '"'"'{ print $1; }'"'"' | xargs -r git branch -d'
Enter fullscreen mode Exit fullscreen mode

The alias prune-no-longer-exist will be available after executing the above command.

It can be used as follows

 $ git prune-no-longer-exist                                                                                                                                               
 Deleted branch xxxxx-account (was 9907023).
 Deleted branch xxxxx-account-accomplish (was 4b1bc41).
 Deleted branch xxxxx-to-gitignore (was 4154555).
 Deleted branch dependabot/bundler/puma-5.6.4 (was b8cf408).
Enter fullscreen mode Exit fullscreen mode

Unnecessary branches are removed from the local machine to refresh it.

I referred to the following.

Top comments (2)

Collapse
 
saltyshiomix profile image
Shiono Yoshihide

What about git fetch --prune option?

Collapse
 
snaka profile image
Shinji NAKAMATSU

Thanks for your comment.
I have already done that by setting git config --global fetch.prune true.
But sometimes branches are left behind ( I'm not sure in what case they are not deleted... ๐Ÿ˜… )