Hi git gurus!
I am supporting a few projects on GitHub, I’m at a point where I have hundreds of branches across all projects and deleting the branches manually is not really an option.
Does anyone have a script on hand to delete all merged branches which do not have any new commits since a specific date?
Any help will be appreciated!
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Hi there @bitmap,
I had a similar case recently. Here are a couple of Bash scripts that might help you.
Delete remote inactive git branches since a specific date
The following script as it is can be used to delete old branches that have been merged and had no activity since a specific date:
A quick rundown of the script:
git fetch
command--merged
flag so that the script would delete all branches no matter if merged or not--since='Jun 15, 2020'
date indicates the date since the branch has been last worked on. The above exmaple will delete all branches that have been idle (eg. no commits or any other activity) sinceJun 15, 2020
. Update it with the date that matches your needs.The script as it is will only give you a list of the branches, to make it actually delete those branches, uncomment the
#git push origin --delete ${remote_branch}
line by deleting the first#
sign.Delete remote branches for multiple projects
In case you are managing multiple projects, what you could do is add a list of your projects in a file called
projects.txt
for example and put a list of your projects, each on a new line.The file needs to be in the same directory as the Bash script.
The script is quite similar to the one above but includes an extra
for
loop which would loop through all of the projects that you’ve specified in theprojects.txt
file.Conclusion
Make sure to review the scripts and run them first without the
git push origin --delete
command to make sure that you are not going to delete any important branches.For more information about git make sure to checkout the following tutorials:
DigitalOcean Git Tutorials
Top 18 Git commands that you should know
Hope that this helps!
Regards, Bobby
Deleting remote branches To delete a remote branch, you can’t use the git branch command. Instead, use the git push command with --delete flag, followed by the name of the branch you want to delete. You also need to specify the remote name (origin in this case) after git push.