Useful Git Tricks

I'm always looking for quick scripts that will make life easier...


Deleting branches already merged into main

Open git bash and navigate to your git repository that you want to clean up

Fetch the latest from the repo:

git fetch


See the list of local git branches

git branch


Delete all local branches that have been merged to the main branch

git switch main

git branch --merged main | grep -v "^\* main" | xargs -n 1 -r git branch -d


See the list of local git branches that remain

git branch


Rebasing to master

git pull --rebase origin master


Merging master branch

$ git checkout validator

$ git merge origin/main

$ git push

Deleting Local Branches That No Longer Exist on the Remote

Open git bash and navigate to your git repository that you want to clean up

Fetch the latest from the repo

git fetch


See the list of local git branches

git branch


Delete all local branches that have been deleted from the main branch

git switch main

git branch -vv | grep ': gone]' | grep -v '\*' | awk '{ print $1; }' | xargs -r git branch -d


Remove all branches except current

git branch | grep -v "main" | xargs git branch -D