Git Branch Cheat Sheet

Here’s a basic cheat sheet for working with branches in Git:

Create a New Branch:

git branch branch_name

Switch to a Branch:

git checkout branch_name
# or
git switch branch_name (Git 2.23 and later)

Create and Switch to a New Branch:

git checkout -b new_branch_name
# or
git switch -c new_branch_name (Git 2.23 and later)

List All Branches:

git branch

Delete a Local Branch:

git branch -d branch_name
# or force delete
git branch -D branch_name

Push a New Branch to Remote:

git push -u origin branch_name

Switch to the Master (or Main) Branch:

git checkout master
# or
git switch master (Git 2.23 and later)

Merge a Branch:

# Switch to the branch you want to merge into
git checkout master
# Merge the branch into the current branch
git merge branch_name

Rename a Branch:

git branch -m new_branch_name

Show the Last Commit on Each Branch:

git branch -v

Track Remote Branch:

git branch -u origin/branch_name

List Remote Branches:

git branch -r

Fetch All Remote Branches:

git fetch --all

Delete a Remote Branch:

git push origin --delete branch_name

Compare Branches:

# Compare branches in a side-by-side view
git difftool branch1..branch2

View Merged and Unmerged Branches:

# List branches merged into the current branch
git branch --merged
# List branches not yet merged
git branch --no-merged

Squash Commits Before Merging:

git rebase -i HEAD~n
# Squash or fixup commits as needed

Undo Last Commit on a Branch:

git reset --soft HEAD^

These commands cover some common scenarios for working with Git branches. Adjust them based on your specific needs. For more details and advanced usage, refer to the official Git documentation.