Here’s how to remove local branches that no longer exist on your Git origin:
Remove Local Branches Not on Origin
To clean up your local repository by deleting branches that have been removed from the remote (origin), you’ll use two main commands:
- Fetch with Prune: This command updates your remote-tracking branches and removes any that no longer exist on the remote.
git fetch --prune
Alternatively, you can use the shorthand:
git fetch -p
- Delete Local Branches: After pruning, you can see which local branches are tracking a remote branch that no longer exists. To delete these, you’ll need to use a loop or identify them manually. A common approach is:
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -d
git branch -vv
: Lists all local branches, showing their upstream branch and commit status.grep ': gone]'
: Filters for branches whose remote tracking branch is gone.awk '{print $1}'
: Extracts just the branch name.xargs git branch -d
: Deletes each of those branches.
If you have any branches that haven’t been fully merged and you want to force delete them (use with caution!), change -d
to -D
:
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D
This process ensures your local repository stays clean and synchronized with the remote, avoiding clutter from stale branches.