How to delete a branch locally and remotely after it has been merged into main
I contributed to a friend’s repository and created a branch locally, then pushed the branch to my forked repo. My friend accepted the changes, so now I can delete my branch locally:
Sometimes Git shows a message that it can’t delete the branch because it detects that it’s not merged, and then suggests that you can force the deletion with the uppercase flag -D instead of -d. However, you must be sure of what you’re doing if you use -D to force the deletion:
If you have several branches to delete, you can use:
To delete all local branches that have been merged into the main branch:
| |
This command switches to the main branch, list all merged branches, excludes the current branch, and deletes each merged branch.
To delete the branch remotely:
For more advanced users, you can create a Git hook to automatically delete branches after merging. Create a file named post-merge in the .git/hooks directory with the following content:
#!/bin/sh
BRANCH=
if ; then
fi
This script will delete the branch after merging if it’s not the main branch.