We can use Git hooks to automatically remove branches after they’re deleted from GitHub.

Building our Git hook

  1. Configure Git to automatically prune remote branches on fetch. This way, if a branch’s remote is deleted, that information will be updated locally whenever we pull from the remote.
    git config --global fetch.prune true
    
  2. Configure a Git hook to remove branches with deleted remotes. We can configure a centralized hooks directory for all repositories on our system.

    mkdir -p ~/.git-hooks
    git config --global core.hooksPath ~/.git-hooks
    # list all branches. ignore current branch (starts with `*`). select branches with deleted remotes. select branch
    echo "
    # list all branches
    git branch -vv | \
    # ignore current branch (prefixed with *)
    grep -vE '^\*' | \
    # select branches with deleted remote
    grep -E '\[.*: gone\]' | \
    # pick branch names
    awk '{ print $1 }' | \
    # delete branchs
    xargs git branch -D
    " >> ~/.git-hooks/pre-push
    

Now our old branches will be removed whenever we push to our remote.