Git Branching - Cheatsheet for Command Line

by John April 18, 2025



 I have always found using git branches and merges a highly traumatic process, and I am totally sick of going through the same thing each time. So in this cheat sheet I will list all the git branch / merge issues and explanations I come across day-to-day. 

 


 

New branch -> Commit -> Merge Flow

 

Create a new branch & switch to it in one line 

git checkout -b new_branch_name

Make changes on new_branch_name & checkout main (or whatever branch you wanna switch to) 

git checkout main

Merge changes 

git merge new_branch_name

 


 

List, Prune & sync Local & Remote Branches (housekeeping)

 

1️⃣ List Branches on Github

 

git fetch && git branch -r

 

Remove Stale Refs locally (i.e. ones that have been merged & deleted on Github) Output in red indicates deleted. 

 

git fetch --prune && git branch -r

'''
 - [deleted]         (none)     -> origin/refactor
 - [deleted]         (none)     -> origin/cleanUP
'''

 

2️⃣List Local Branches 

 

git branch

git branch -v ## gives more info

 

Remove all local branches that have been deleted on Github sparing the ones that are still unmerged locally, (see output below)

 

git branch -vv | grep '\[origin/.*: gone\]' | awk '{print $1}' | xargs -r git branch -d


'''
<!-- deletes only branches that remote version marked as gone --> 
Deleted branch cleanup (was 2c6f1d6).
Deleted branch cleanup1 (was 4675eed).

<!-- Have to do these manually if you want them gone --> 
error: The branch 'CleanUp' is not fully merged.
If you are sure you want to delete it, run 'git branch -D CleanUp'.
'''

 

Can Also force delete them if things have piled up (careful you don't have unmerged branches or they get trashed)

git branch -vv | grep '\[origin/.*: gone\]' | awk '{print $1}' | xargs -r git branch -D