Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Managing Branches is an important part of the software development process. Over time, Branches can accumulate and become difficult to manage. When we work in a company with many developers, there can be situations where the repositories become unwieldy and need to be maintained in order to remove clutter and make the repository more organized. However, this is a very complicated and manual job, to git delete remote branch.
In this article, I’ll show you a Shell Script that can help you automate the cleanup of Branches that have already been merged with Branch dev.
Table of Contents
Effective branch management in a Git repository plays a crucial role in maintaining a clean and organized development environment.
When development teams collaborate on projects, multiple branches are created. However, these branches often become outdated after the completion of a feature or a bug fix. As a result, failing to remove these outdated branches can lead to several issues. One of the main problems is the occurrence of unnecessary conflicts.
Additionally, the accumulation of outdated branches can lead to increased complexity of the repository, making it challenging to understand and navigate.
Finally, this neglect can also make it challenging to identify active branches, since obsolete branches are still present.
It is in this context that the branch cleaning script in Git comes into play. This script that I will provide automates the process of identifying and removing branches that have already served their purpose, simplifying the Git Branch Cleanup process, thus keeping the Git repository more organized and efficient. Its importance extends to several areas:
In summary, using a branch cleanup script in Git is a best practice for maintaining order and efficiency in a branch environment / Collaborative development. It helps avoid common problems associated with improper branch management and contributes to a smoother, more productive workflow, allowing developers to focus on what really matters: writing high-quality code and delivering software more effectively.
In my scenario, we use the “dev” branch a lot, which normally receives the merge of several branches where the teams are working. However, even though there is an option to select that branch to be deleted during the Pull Request closing process, many branches are left behind, making the repository heavier.
To solve this, I created this script:
#!/bin/sh
date=$(date +"%d%m%Y")
echo ${date}
# Efetuando checkout para a Branch dev
git checkout dev
# Salvando relatórios com as listagens das Branches remotas e as Branches que já foram mergeadas
git branch -r --merged | tee /devops/branch_list_dev_${date}.txt
git branch -r --merged | grep --invert-match dev | tee /devops/branch_list_merged_dev_${date}.txt
# Efetuando a limpeza de Branches que já foram mergeadas com a Branch dev
git branch -r --merged | grep --invert-match dev | grep --invert-match HEAD | grep -v "am-alert" | grep "origin/" | cut --d "/" -f 2- | xargs -n 1 git push --delete origin
This script is a shell (bash) script that runs a series of commands related to Git version control, to git delete branch local and remote. Here’s a step-by-step explanation of what each part of the script does:
date=$(date +"%d%m%Y")
: This line gets the current date and formats it in the format “DDMMYYY” (day, month and year) and stores the value in a variable called date
.echo ${date}
: This line prints the formatted date to the console.git checkout dev
: This command switches to the branch called “dev” using Git. This means that the script is now working on the “dev” branch.git branch -r --merged | tee /devops/branch_list_dev_${date}.txt
: This command lists all remote branches that were merged into the “dev” and redirects the output to a file called “branch_list_dev_data.txt”. The tee
is used to show the output in the console and also save it to the file.git branch -r --merged | grep --invert-match dev | tee /devops/branch_list_merged_dev_${date}.txt
: This command lists all remote branches that have been merged, except the “dev” branch, and redirects the output to a file called “ ;branch_list_merged_dev_data.txt”.git branch -r --merged | grep --invert-match dev | grep --invert-match HEAD | grep -v "am-alert" | grep "origin/" | cut --d "/" -f 2- | xargs -n 1 git push --delete origin
: This command performs a series of actions:xargs
to iterate over these branches and runs the command git push --delete origin
to delete each one remotely.In short, this script is used to list the remote branches that have been merged into the dev
branch, save these lists to files based on date, and subsequently delete these remote branches (except dev
) that were merged. This tool is valuable for cleaning up old branches that have already been merged into a Git repository. It is critical to make sure you fully understand how each command works before running the script in a production environment.
Q: What does the script do?
A: The script automates the process of identifying and removing outdated branches in Git. It checks out the dev
branch, saves reports of merged and remote branches, and deletes merged branches that are not the dev
branch or HEAD
.
Q: How do I use the script?
A: Save the script to a file, make it executable, and run it with the command ./git_branch_cleanup.sh
.
Q: Can I customize the script?
A: Yes, you can customize the script to fit your team’s specific needs, such as excluding specific branches or adding additional checks.
Q: How often should I run the script?
A: It’s recommended to schedule the script to run regularly, such as daily or weekly, to ensure that the Git repository remains clean and organized.
Q: Is it safe to delete merged branches?
A: Yes, it’s safe to delete merged branches as long as they are not the dev
branch or HEAD
. The script excludes these branches from deletion.
Q: What if I need to restore a deleted branch?
A: If you need to restore a deleted branch, you can recreate it from the remote repository or use Git’s reflog to restore it.
Q: Can I test the script before using it in a production environment?
A: Yes, it’s recommended to test the script thoroughly before using it in a production environment.
Q: How do I manage changes to the script over time?
A: Use version control to manage the script and track changes over time.
Q: What if I encounter an error while running the script?
A: Check the script’s output for any error messages and investigate the issue. If you’re unable to resolve the issue, seek help from a Git expert or consult the script’s documentation.
Q: Can the script be used with other Git branches besides dev
?
A: Yes, the script can be modified to work with other Git branches besides dev
. Simply replace the dev
branch name in the script with the desired branch name.
It is crucial to make sure you fully understand how the script works, as it performs actions that are difficult to reverse. Thus, by taking due care, you can create routines where this script is executed periodically, ensuring that you obtain the expected benefits without any unwanted impacts.
Using a branch cleanup script in Git represents an essential measure to maintain the integrity and efficiency of a source code repository. By automating the process of identifying and removing obsolete branches, this script plays a key role in promoting an organized and hassle-free development environment.
Furthermore, proper branch management not only increases project clarity and understanding, but also enhances collaboration between team members. This, in turn, significantly reduces the likelihood of conflicts, saves disk space, strengthens security, and boosts overall repository performance.
Ultimately, the practice of regular branch cleanup is an essential component of the sustainable health of the project, allowing the development team to focus on its main goals and objectives. Therefore, by adopting and maintaining a branch cleanup script as an integral part of your workflow, you are making a valuable investment in the quality and efficiency of software development, thereby contributing to the creation of better, more robust products. Don’t underestimate the value of this seemingly simple yet surprisingly powerful tool in your development journey.
More questions about the DevOps world and other specific questions about Git?
Access our articles about git:
https://devopsmind.com.br/en/category/git-en-us
Also, feel free to contact our team for personalized help.
*Disclaimer: The information provided in this article is for educational purposes only.