Cleaning up the environment after a successful sprint is probably my favorite part so far. This includes everything from Git branches to containerized application environments. It’s a risk-free if you are doing it on your own repos; however, when working with other people it’s a best practice not to remove any remote branch by your own as there must be Git branch configuration and policies in place.
Prerequisites
- Git
Solution
Local branches
Remove a single branch:
git branch -D <branch_name>
Remove multiple branches:
git branch -D <branch_1> <branch_2>
Delete all local branches except master
.
git branch | grep -v "master" | xargs git branch -D
Note: In case you are working with a main
branch instead of master
, replace master
with main
.
Yet, if you need to preserve the develop
branch as well, run:
git branch | grep -v "master\|develop" | xargs git branch -D
Delete every local branch except the current one.
git branch | grep -v `git branch --show-current` | xargs git branch -D
Delete any local branches that start with prefix feature/
.
git branch -D $(git branch --list 'feature/*')
To delete all local branches that are already merged to main
, run:
git branch -r --merged main | grep -v main | sed 's/origin\///' | xargs -n 1 git branch -D
Remote branches
Remove single remote branch:
git push origin --delete <branch_name>
Remove more than a single remote branch:
git push origin --delete <branch-1> <branch-2>
Delete any remote branch but main
.
git branch | grep -v "main" | xargs git push origin --delete
Delete any remote branch except main
and develop
.
git branch | grep -v "main\|develop" | xargs git push origin --delete
To delete all branches on remote that are already merged to main
, run:
git branch -r --merged main | grep -v main | sed 's/origin\///' | xargs -n 1 git push --delete origin
Finally, delete the remote tracking branch (this will remove the local copy of the branch) with:
git fetch origin --prune
Conclusion
Related posts:
To find more neat Git commands and hacks, simply browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.