Git Avanzato — Cheat Sheet

Tags: git, rebase, merge, bisect, reflog, hooks

Level: advanced

TL;DR: A quick reference for advanced Git operations, including rebasing, resolving complex conflicts, tracking down bugs, and recovering lost commits.

Key concepts

-

Rebase vs Merge: Rebase rewrites history for a linear path; merge preserves explicit branching history.

-

Interactive Rebase: Allows squashing, editing, reordering, or dropping previous commits cleanly.

-

Reflog: A local log of where HEAD and branches have been, essential for recovering lost commits.

-

Cherry-pick: Applies the changes introduced by specific existing commits to the current branch.

-

Bisect: Uses binary search to find the exact commit that introduced a bug.

-

Worktrees: Allows checking out multiple branches simultaneously in separate directories sharing the same repository.

-

Hooks: Scripts that run automatically before or after events like commit, push, or receive.

-

Stash: Temporarily shelves incomplete changes to allow working on a different branch without committing.

Typical questions and ready answers

-

Q: How do you recover a dropped commit after a hard reset?R: I check git reflog to find the lost commit's SHA, then I use git cherry-pick <SHA> or branch from it.

-

Q: What is the difference between git merge --squash and a standard merge?R: Squash combines all branch commits into a single new commit on the target branch, keeping history clean without merge nodes.

-

Q: When should you absolutely avoid rebasing?R: I never rebase commits that have already been pushed to a shared branch, as it diverges history for teammates.

Pitfalls and common mistakes

-

Force pushing (--force) on shared branches overwrites remote work; always prefer --force-with-lease.

-

Forgetting to update the base branch before an interactive rebase can lead to cascading merge conflicts.

-

Abusing git stash without descriptive names makes finding old stashed work extremely difficult.

Snippets and commands

# Interactive rebase of the last 3 commits
git rebase -i HEAD~3

# Find the commit that broke a feature
git bisect start
git bisect bad HEAD
git bisect good <working_commit_hash>

# Recovering from reflog
git reflog
git reset --hard HEAD@{2}

# Safe force push
git push origin <branch> --force-with-lease

# Create a new worktree
git worktree add ../new-feature-dir <branch-name>

To review

-

[ ] Advanced conflict resolution using git mergetool

-

[ ] Writing custom pre-commit hooks for automated linting

References

-

Pro Git Book (official documentation)

Jarvis Interviews
Jarvis