Complete Distributed Version Control (Git) Cheat Sheet – Commands, Workflows & Best Practices

Introduction

Distributed Version Control Systems (DVCS) allow multiple developers to work on the same project simultaneously while maintaining a complete history of changes. Unlike centralized systems, every developer has a full copy of the project history, enabling offline work and reducing single points of failure. Git is the most popular DVCS, powering platforms like GitHub, GitLab, and Bitbucket.

Why DVCS Matters:

  • Complete project history on every machine
  • Offline capabilities
  • Superior branching and merging
  • Enhanced collaboration workflows
  • Better backup and redundancy

Core Concepts & Principles

Repository Structure

  • Working Directory: Your local files and folders
  • Staging Area (Index): Prepared changes ready to commit
  • Local Repository: Your complete project history
  • Remote Repository: Shared repository (GitHub, GitLab, etc.)

Key Principles

  • Snapshots, Not Differences: Git stores complete snapshots of your project
  • Integrity: Everything is checksummed with SHA-1 hashes
  • Three States: Modified, Staged, Committed
  • Branching: Lightweight, fast branch creation and switching
  • Distributed: No central authority required

Essential Git Configuration

Initial Setup

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global init.defaultBranch main
git config --global core.editor "code --wait"

Useful Configuration

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.unstage 'reset HEAD --'

Basic Git Commands by Category

Repository Operations

CommandDescriptionExample
git initInitialize new repositorygit init my-project
git cloneClone remote repositorygit clone https://github.com/user/repo.git
git statusCheck repository statusgit status
git logView commit historygit log --oneline --graph

File Operations

CommandDescriptionExample
git addStage changesgit add file.txt or git add .
git commitCommit staged changesgit commit -m "Add new feature"
git rmRemove filesgit rm file.txt
git mvMove/rename filesgit mv old.txt new.txt
git restoreRestore filesgit restore file.txt

Branch Operations

CommandDescriptionExample
git branchList/create branchesgit branch feature-xyz
git checkoutSwitch branchesgit checkout main
git switchSwitch branches (new)git switch feature-xyz
git mergeMerge branchesgit merge feature-xyz
git rebaseRebase branchesgit rebase main

Remote Operations

CommandDescriptionExample
git remoteManage remotesgit remote add origin <url>
git fetchDownload remote changesgit fetch origin
git pullFetch and mergegit pull origin main
git pushUpload changesgit push origin main

Git Workflow Methodologies

1. Centralized Workflow

Best for: Small teams, simple projects

  • Single main branch
  • All changes committed directly to main
  • Linear history
git clone <repository>
# Make changes
git add .
git commit -m "Description"
git push origin main

2. Feature Branch Workflow

Best for: Medium teams, feature-based development

  • Create branches for each feature
  • Merge back to main when complete
git checkout -b feature/user-auth
# Develop feature
git add .
git commit -m "Implement user authentication"
git push origin feature/user-auth
# Create pull request
git checkout main
git merge feature/user-auth

3. Gitflow Workflow

Best for: Release-based projects, larger teams

  • main: Production-ready code
  • develop: Integration branch
  • feature/*: New features
  • release/*: Release preparation
  • hotfix/*: Emergency fixes

4. GitHub Flow

Best for: Continuous deployment, web applications

  • Create branch from main
  • Add commits
  • Open pull request
  • Deploy and test
  • Merge to main

Advanced Git Commands

History and Inspection

CommandDescriptionExample
git diffShow changesgit diff HEAD~1
git showShow commit detailsgit show abc1234
git blameShow line authorsgit blame file.txt
git bisectBinary search for bugsgit bisect start

Undoing Changes

CommandDescriptionExample
git resetReset to previous stategit reset --soft HEAD~1
git revertCreate reverse commitgit revert abc1234
git reflogShow reference loggit reflog
git cherry-pickApply specific commitgit cherry-pick abc1234

Stashing

CommandDescriptionExample
git stashSave temporary changesgit stash push -m "WIP"
git stash popApply and remove stashgit stash pop
git stash listList all stashesgit stash list
git stash dropDelete stashgit stash drop stash@{0}

Branching Strategies Comparison

StrategyProsConsBest For
Single BranchSimple, easy to understandNo isolation, conflicts commonSolo projects, prototypes
Feature BranchesIsolated development, clean historyMerge conflicts, overheadMost team projects
GitflowStructured, handles releases wellComplex, slower developmentEnterprise, scheduled releases
GitHub FlowSimple, continuous deploymentLess control over releasesWeb apps, SaaS products

Common Challenges and Solutions

Merge Conflicts

Problem: Conflicting changes in same file lines Solution:

git status  # See conflicted files
# Edit files to resolve conflicts
git add resolved-file.txt
git commit -m "Resolve merge conflict"

Accidental Commits

Problem: Committed wrong files or messages Solutions:

# Undo last commit, keep changes
git reset --soft HEAD~1

# Undo last commit, discard changes
git reset --hard HEAD~1

# Amend commit message
git commit --amend -m "Corrected message"

Large Files

Problem: Repository becomes bloated Solutions:

  • Use .gitignore for build artifacts
  • Implement Git LFS for large files
  • Use git clean -fd to remove untracked files

Detached HEAD

Problem: Working in detached HEAD state Solution:

# Create branch from current state
git checkout -b new-branch-name

# Or return to main branch
git checkout main

Best Practices and Tips

Commit Guidelines

  • Write clear commit messages: Use imperative mood (“Add feature” not “Added feature”)
  • Make atomic commits: One logical change per commit
  • Commit frequently: Small, focused commits are easier to track
  • Use conventional commits: feat:, fix:, docs:, refactor:

Branch Management

  • Use descriptive branch names: feature/user-authentication, bugfix/login-error
  • Keep branches short-lived: Merge frequently to avoid conflicts
  • Delete merged branches: Clean up after merging
  • Protect main branch: Use branch protection rules

Repository Organization

  • Maintain .gitignore: Exclude build files, IDE settings, secrets
  • Use README.md: Document project setup and usage
  • Tag releases: Use semantic versioning (v1.2.3)
  • Regular maintenance: Clean up old branches and tags

Collaboration Tips

  • Pull before push: Always sync with remote before pushing
  • Use pull requests: Enable code review and discussion
  • Write descriptive PR descriptions: Explain what and why
  • Review code thoroughly: Check for bugs, style, and logic

Git Aliases for Productivity

# Status and log shortcuts
git config --global alias.s status
git config --global alias.l "log --oneline --graph --decorate"
git config --global alias.ll "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'"

# Branch shortcuts
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.sw switch

# Useful combinations
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'

Troubleshooting Quick Reference

ProblemCommandDescription
See what changedgit diffCompare working directory to staging
Undo unstaged changesgit restore file.txtDiscard changes in working directory
Unstage filesgit restore --staged file.txtRemove from staging area
See commit historygit log --onelineCondensed commit history
Find when bug introducedgit bisect startBinary search through commits
Recover deleted branchgit reflogFind branch reference
Clean untracked filesgit clean -fdRemove untracked files and directories

Advanced Workflows

Rebase vs Merge Decision Matrix

ScenarioUse RebaseUse Merge
Feature branch to main
Updating feature branch
Shared branch
Public commits
Preserving context
Clean linear history

Git Hooks Examples

# Pre-commit hook (run tests)
#!/bin/sh
npm test
if [ $? -ne 0 ]; then
  echo "Tests must pass before commit!"
  exit 1
fi

# Pre-push hook (prevent force push to main)
#!/bin/sh
protected_branch='main'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
if [ $protected_branch = $current_branch ]; then
  echo "Direct push to main branch is not allowed"
  exit 1
fi

Resources for Further Learning

Official Documentation

  • Git Official Documentation: https://git-scm.com/doc
  • Pro Git Book: https://git-scm.com/book (Free online)
  • Git Reference: https://git-scm.com/docs

Interactive Learning

  • Learn Git Branching: https://learngitbranching.js.org/
  • GitHub Skills: https://skills.github.com/
  • Atlassian Git Tutorials: https://www.atlassian.com/git/tutorials

Advanced Topics

  • Git Internals: Understanding how Git works under the hood
  • Git Workflows: Comparing different team collaboration strategies
  • Git Hooks: Automating tasks with Git hooks
  • Git LFS: Managing large files in Git repositories

Tools and GUIs

  • GitKraken: Cross-platform Git GUI
  • SourceTree: Free Git GUI by Atlassian
  • VS Code Git Integration: Built-in Git support
  • GitHub Desktop: Simple Git GUI for GitHub

Command Line Enhancements

  • Oh My Zsh Git Plugin: Enhanced Git aliases and prompts
  • Git Flow Extensions: Tools for Gitflow workflow
  • Tig: Text-based Git repository browser
Scroll to Top