Git Beyond Basics
Branching strategies, rebasing vs merging, cherry-picks, and stashing. The skills that separate juniors from seniors.
Branching
Branches are cheap in Git. Create one for every feature, bug fix, or experiment. The convention is feature/name, fix/name, or hotfix/name. Keep them short-lived and merge them quickly.
# Create and switch to a new branch
git checkout -b feature/user-auth
# List all branches (local and remote)
git branch -a
# Switch to an existing branch
git checkout main
# Delete a branch (local)
git branch -d feature/old-branch
# Delete a remote branch
git push origin --delete feature/old-branch
# Rename current branch
git branch -m new-branch-nameMerging
Merging combines two branches. If Git cannot auto-merge (both branches changed the same line), you get a conflict. Do not panic - conflicts are normal. Open the file, pick the right code, remove the markers, and commit.
# Merge a feature branch into main
git checkout main
git merge feature/user-auth
# If there are conflicts, Git marks them in the files:
# <<<<<<< HEAD
# your code on main
# =======
# their code from the branch
# >>>>>>> feature/user-auth
# After resolving conflicts:
git add .
git commit -m "Merge feature/user-auth into main"Rebasing - Clean History
Rebasing replays your commits on top of another branch, creating a linear history. The golden rule: never rebase commits that have been pushed and shared with others. Use rebase to clean up your local commits before merging.
# Rebase your branch onto latest main
git checkout feature/user-auth
git rebase main
# Interactive rebase - squash last 3 commits into one
git rebase -i HEAD~3
# Change "pick" to "squash" (or "s") for commits to combine
# If rebase has conflicts, fix them then:
git add .
git rebase --continue
# Abort a rebase if things go wrong
git rebase --abortCherry-Pick - Surgical Commits
Cherry-pick takes a single commit from one branch and applies it to another. Useful for hotfixes - fix the bug on your feature branch, then cherry-pick just that fix onto main.
# Apply a specific commit to your current branch
git cherry-pick abc1234
# Cherry-pick without committing (just stage the changes)
git cherry-pick abc1234 --no-commit
# Cherry-pick a range of commits
git cherry-pick abc1234..def5678Stashing - Save for Later
You are mid-feature when an urgent bug comes in. You cannot commit half-finished code, but you cannot switch branches with uncommitted changes. Stash saves your work, cleans your working directory, and lets you come back to it later.
# Stash your current changes
git stash
# Stash with a descriptive message
git stash push -m "WIP: user auth validation"
# List all stashes
git stash list
# Apply the most recent stash (keep it in the list)
git stash apply
# Apply and remove from the list
git stash pop
# Apply a specific stash
git stash apply stash@{2}
# Drop a specific stash
git stash drop stash@{0}