gitgithubbitbucketbranching-and-merging

Delete Local Development Branch Automatically after Merge on GitHub


I am trying to figure out a way that after my local development branch has been pushed up to GitHub, or BitBucket, or whichever VCS, and a pull request has been approved, when that branch is merged into main, is there some sort of script or functionality that would allow the local development branch to be automatically deleted on my local system.

I'm not specifically referring to the git branch --delete command, which obviously I can do manually, but rather have that branch be deleted from my local machine, after I check out into main, and do a fresh git pull of that very development branch that was previously merged in already.

What I am looking to do is:

  1. Push up changes to local-branch.
  2. Merge local-branch into main after PR is approved, in the browser.
  3. On my local system, check out into main and git pull the changes from the recently merged local-branch.
  4. Have local-branch be deleted locally on my system, so when running git branch, that branch is no longer listed.

Is this doable somehow? I hope that all made sense...

EDIT: Just some more info, so we use BitBucket as our VCS, and after the local-branch is merged with the BitBucket interface's Merge button, that local-branch is not deleted on BitBucket, which is a company decision, but I am just looking to have it deleted on my local system after pulling the latest main, after local-branch has been merged.


Solution

  • Go over branches from git branch -r --merged origin/main and delete the corresponding local branches

    If your local branch names are the same as the remote branch names, the following script will delete all the local branches whose names are the same as the remote branches if they were already merged into the $REPO_MAIN branch. You can replace git branch -d with git branch -D when you want to delete the branch forcefully and I think -D will better suit your need.

    REMOTE=origin
    REPO_MAIN=main
    for remote_branch in $(git branch -r --merged "$REMOTE"/"$REPO_MAIN" | grep -v "$REMOTE"/"$REPO_MAIN" | grep -v 'HEAD'); do
      branch_name=${remote_branch#"$REMOTE"/}
    
      # Check if local branch exists
      if git show-ref --verify --quiet refs/heads/"$branch_name"; then
        echo "Deleting local branch: $branch_name"
        git branch -d "$branch_name"
      else
        echo "No local branch for: $branch_name"
      fi
    done