git delete remote branch

Git delete remote branch: Automate with this Script

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.

git delete remote branch
Imagem de freepik

Main problems

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.

Importance of branch cleaning in Git

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:

  1. Organization and Clarity: Maintaining a clean Git repository free of obsolete branches helps developers better understand the project structure. This makes it easier to navigate, search for relevant code, and understand the relationships between different parts of the software.
  2. Conflict Reduction: Old and unused branches can cause unnecessary conflicts during the code merge process. Properly removing these branches reduces the likelihood of conflicts and simplifies the code integration process.
  3. Space Saving: The Git repository can grow considerably over time due to the accumulation of data from old branches. Deleting these branches helps save disk space, making the repository more storage efficient.
  4. Security: Deleting branches that are no longer needed also contributes to security. This helps prevent unauthorized access to legacy code or branches that contain sensitive information.
  5. Performance Improvement: A cleaner Git repository tends to perform better in git operations such as cloning, checkout and merging. This is especially important for teams working on large projects.

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.

Script – Git delete remote branch

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:

  1. 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.
  2. echo ${date}: This line prints the formatted date to the console.
  3. 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.
  4. 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.
  5. 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”.
  6. 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:
    • It lists all the remote branches that were merged, except the “dev” branch.
    • It deletes any line that mentions “HEAD”.
    • It deletes any line that contains the word “am-alert”.
    • It only filters branches that start with “origin/”.
    • Then it cuts off the “origin/” of the remaining lines.
    • Finally, it uses 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.

git delete branch local and remote

Use Cases

  • Maintaining a Clean Repository: Regularly running the script helps keep your repository organized and easy to navigate, reducing the risk of errors and conflicts.
  • Automating Repository Maintenance: Integrate the script into your CI/CD pipeline or schedule it using a cron job to automate the cleanup process.
  • Collaboration: Share the script with your team to ensure everyone follows the same cleanup process, promoting consistency and efficiency.

FAQ

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.

Best Practices

  • Backup your Repository: Before running the script, ensure that you have a backup of your repository. This will help you recover any accidentally deleted branches.
  • Test the Script: Test the script on a non-critical repository or a test branch to ensure it works as expected.
  • Schedule Regular Cleanups: Schedule the script to run periodically, such as weekly or monthly, to maintain a clean repository.
  • Communicate with Your Team: Inform your team about the cleanup process and the schedule to avoid any surprises or potential conflicts.

Important note

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.


Conclusion

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.

Additional Resources

Source

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.

Compartilhe / Share
Fernando Müller Junior
Fernando Müller Junior

I am Fernando Müller, a Tech Lead SRE with 16 years of experience in IT, I currently work at Appmax, a fintech located in Brazil. Passionate about working with Cloud Native architectures and applications, Open Source tools and everything that exists in the SRE world, always looking to develop and learn constantly (Lifelong learning), working on innovative projects!

Articles: 36

Receba as notícias por email / Receive news by email

Insira seu endereço de e-mail abaixo e assine nossa newsletter / Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *