Git User Guide
Everyday Reference
Git is a distributed version control system that tracks file modifications and enables secure, coordinated collaboration across development environments. This reference architecture manual provides a comprehensive look at Git's core operational mechanics, progressing from an everyday command syntax cheat sheet into deep-dives on system configuration, private and collaborative execution loops, code archaeology, and disaster recovery. Use this cheat sheet for rapid access to the most frequently executed version control operations.
Stage & Commit
git status
git add .
git commit -m "feat: message"
git commit --amend --no-edit
Branch Navigation
git branch --sort=-committerdate
git switch feature-branch
git switch -c new-branch
git branch -d old-branch
File Restoration
git restore config.json
git restore --staged config.json
git restore -s HEAD~1 file.js
git clean -fd
Synchronization
git fetch origin --prune
git pull --rebase origin main
git push -u origin feature
git push --force-with-lease
Stash Management
git stash push -m "wip: label"
git stash list
git stash show -p stash@{0}
git stash pop
Quick Diagnostics
git log --oneline --graph
git diff --staged
git diff main...feature
git reflog
Data Transport Mechanics
Under the hood, the software operates as a content-addressable filesystem implemented primarily in C, Shell, Perl, and Tcl. Rather than recording sequential delta diffs, the system stores data as an immutable stream of snapshots compressed via cryptographic SHA hashing. Every time a commit executes, the engine captures a structural reference to the entire workspace. Files that have not mutated simply link to the identical compressed object stored during prior transactions.
The Four Storage Zones
Understanding Git requires mapping operational movement across four isolated storage environments within your local and cloud infrastructure:
- Working Directory: The physical files sitting on your local disk. Tracked modifications here remain unsaved in transaction history until explicitly staged.
- Staging Area (The Index): A structured binary file inside the hidden
.gitdirectory that caches the exact cryptographic checksums and file contents queued for the next commit snapshot. - Local Repository: The private database inside
.git/objectsrecording permanent, immutable commit nodes and pointer references on your local machine. - Remote Repository: Cloud-hosted backup and team synchronization infrastructure (such as GitHub) utilized for exchanging commit graphs.
File State Transitions
Every file tracked by the system resides in one of four precise conditions:
- Untracked: The file exists within your physical disk workspace but has never been added to the staging index.
- Modified: A tracked file has been edited on disk, but those changes remain isolated outside the staging index.
- Staged: Modified contents have been copied onto the loading dock index, prepared for permanent encapsulation.
- Committed: The snapshot has been cryptographically secured inside the local database.
Directional Flow Matrix
git add )
Copies modified working tree files into the binary staging index.
git commit -m "msg")
Wraps index contents into an immutable commit object within the database.
git push origin )
Appends local branch commit nodes onto the corresponding remote server graph.
git fetch origin)
Downloads remote objects and updates remote-tracking pointers without altering disk files.
git pull --rebase)
Fetches remote commits and reapplies local unpushed disk changes sequentially on top.
git restore )
Overwrites physical disk modifications with the last recorded commit snapshot.
git restore --staged )
Evicts files from the index back to modified disk status without deleting edits.
Identity & Authentication
Proper environmental initialization prevents commit attribution errors and establishes linear history defaults automatically across all newly initialized projects.
Global Configuration
# Set identity matching your collaborative profile precisely
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Enforce 'main' as the primary initialization branch globally
git config --global init.defaultBranch main
# Configure pull operations to rebase by default, preventing redundant merge bubbles
git config --global pull.rebase true
# Automatically prune deleted remote tracking references during fetch operations
git config --global fetch.prune true
# Establish shorthand aliases for rapid command execution
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
Multi-Account Authentication
Operating across multiple cloud organizations requires strict identity isolation. When connecting via HTTPS, distinguish accounts by embedding the target username directly into the repository URL. When communicating over SSH, configure distinct cryptographic key pairs routed via host aliases inside your system configuration.
# ~/.ssh/config structure for routing multiple GitHub identities
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
IdentitiesOnly yes
Host github-enterprise
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_enterprise
IdentitiesOnly yes
Credential Helpers and Token Management
Modern operating systems secure authentication tokens using native encrypted storage mechanisms linked via the credential.helper directive. Windows environments rely on wincred, macOS utilizes osxkeychain, and Linux desktop distributions run libsecret. Automated container pipelines can dynamically source credentials by passing shell evaluation commands directly into the configuration.
# Purge stale or corrupted tokens manually from the local credential store
echo url=https://username@github.com | git credential reject
# Authenticate seamlessly using the modern GitHub CLI interface
gh auth login --scopes "repo,read:org"
Solo Private Repository
Operating an independent private repository requires establishing reliable checkpoints while isolating experimental refactoring from your stable production baseline. You can instantiate and link cloud repositories entirely from the command line.
Rapid Terminal Instantiation
# Initialize local repository and set primary branch
git init -b main
# Create initial structural files and execute baseline commit
git add .
git commit -m "chore: initialize project repository"
# Create private remote repository and configure upstream tracking in one sequence
gh repo create my-private-app --private --source=. --remote=origin --push
Path Manipulation & System-Wide Exclusions
Never rely on operating system file managers to move or rename actively tracked source files. Directly execute Git path manipulation commands to preserve historical file lineage and stage structural transformations instantly.
# Rename or relocate a tracked file while immediately updating the staging index
git mv src/utils.js src/helpers/utilities.js
# Remove a file from the repository and stage its deletion
git rm deprecated-config.json
# Stop tracking an actively tracked file without removing it from your physical disk
git rm --cached local-environment.env
# Establish a global exclusion file to block system artifacts across local projects
git config --global core.excludesfile ~/.gitignore_global
Daily Feature Sandbox
Execute everyday version control operations using modern command syntax. Modern Git separates branch switching (git switch) from working directory file restoration (git restore), superseding the overloaded legacy git checkout command.
- Isolate experimental work immediately:
git switch -c feat/database-migration. - Stage specific chunks of code interactively to ensure cohesive commits:
git add -p. - Commit changes with descriptive messages summarizing the architectural intent.
- Synchronize stable production code back into your working branch:
git switch main git merge feat/database-migration git push origin main - Prune completed local and remote feature branches immediately to keep workspace clean:
git branch -d feat/database-migration git push origin --delete feat/database-migration
Collaborative & Team Protocols
Contributing to shared repositories introduces remote state synchronization, peer review gates, and merge conflict resolution. Teams must enforce clean linear histories and strict verification boundaries.
Stash Management
When upstream commits merge onto shared branches while you maintain uncommitted modifications, stash your working state. Advanced stash commands allow selective inspection and targeted stack retrieval without losing unpushed progress.
# Push working modifications onto stash stack accompanied by an explicit identifier
git stash push -m "wip: authentication token parsing"
# Review the numbered, stack-ordered history of all saved local states
git stash list
# Inspect line-by-line patch diffs of a specific stored stash before applying
git stash show -p stash@{0}
# Reapply historical stash modifications without evicting entry from stack
git stash apply stash@{0}
# Permanently drop a specific stash entry after successful validation
git stash drop stash@{0}
Commit Cleanup With Interactive Rebase
Prior to submitting pull requests, developers must clean up messy work-in-progress commits. Interactive rebasing allows you to squash redundant commits, reword unclear descriptions, and reorder historical additions cleanly.
# Initiate interactive rebase targeting the last 5 commits
git rebase -i HEAD~5
# Inside your editor, replace 'pick' with 'fixup' or 'squash' to combine commits
# If upstream changes create conflicts during rebase, resolve files and continue:
git add resolved-file.js
git rebase --continue
# Abort rebase entirely to restore original branch pointers if mistakes occur
git rebase --abort
Long-Lived Branch Merge Strategy: Never perform repeated squash merges between two long-lived branches (such as develop and main). Squash merging generates isolated commits without creating historical common ancestors. Subsequent merges will force your team to repeatedly re-resolve identical merge conflicts. Standard merge commits must be utilized between persistent branches to advance the common ancestry pointer.
Safe Force Pushing
Rewriting branch history via rebasing alters cryptographic SHA hashes, causing your local branch to diverge from remote storage. Pushing altered commit graphs requires force mechanics, but standard force flags risk destroying concurrent commits pushed by teammates.
# CRITICAL SAFETY: Push rebased history safely using lease verification
git push --force-with-lease origin feat/ticket-402
Zero Tolerance for Plain Force Push: Never execute git push --force on collaborative repositories. Always utilize --force-with-lease. This flag validates that your local engine possesses the exact latest SHA hash recorded on the remote server before overwriting cloud storage. If a teammate has pushed code since your last fetch operation, the transfer aborts immediately, preventing catastrophic data loss.
Code Archaeology & History Inspection
Investigating legacy codebases requires precise forensic commands that isolate functional regressions, trace file evolution across historical renames, and pinpoint exact authorship without modifying active disk files.
Range Notations & Commit Ancestry
Navigating complex commit graphs requires mastering range notation symbols and pointer traversal operators:
branchA..branchB(Two-Dot Range): Displays all commits reachable frombranchBwhile excluding commits reachable frombranchA.branchA...branchB(Three-Dot Range): Displays symmetric difference, isolating commits reachable from either branch pointer but excluding shared common ancestors.HEAD~3(Tilde Operator): Navigates strictly backward along the primary linear parent path (e.g., great-grandparent commit).HEAD^2(Caret Operator): Selects the second specific parent commit originating from a multi-parent merge execution.
Forensic Search Sequences
# Trace commit history of a file continuously across historical rename operations
git log --follow --stat -M src/legacy-module.js
# Identify specific user attribution and commit timestamps for lines 40 through 65
git blame -L 40,65 src/services/auth.ts
# Search entire commit history for exact code string additions or deletions
git log -S "legacy_token_secret"
# Search file contents across a specific historical release tag
git grep "database_host" v2.4.0
# Inspect file contents as they existed inside an old commit snapshot
git show a1b2c3d:package.json
Automated Regression Isolation via Bisect
When functional regressions appear within large codebases, executing automated binary search across commit history isolates the exact defect source in minimal steps.
# Initiate binary search debugging sequence
git bisect start
# Mark current broken commit pointer as problematic
git bisect bad
# Mark historical working commit pointer as functional baseline
git bisect good v2.1.0
# Git automatically checks out midpoint commits. Run tests, then mark each step:
git bisect good # or: git bisect bad
# Terminate sequence and restore working branch once culprit SHA is identified
git bisect reset
Platform Integrity & Disaster Recovery
Cross-platform filesystem inconsistencies and aggressive operating system utilities can corrupt repository databases. Enforcing root-level standardization rules protects project integrity.
Filesystem Standardization Rules
Windows and macOS filesystems enforce case-folding, causing files differing only in capitalization (e.g., App.js vs app.js) to register as perpetually modified. Resolve this anomaly by purging duplicate index entries via git rm --cached on a clean working tree. Additionally, configure a root .gitattributes file to enforce uniform line-ending conversion and protect binary artifacts across operating systems.
# Root .gitattributes repository rules
* text=auto
*.js text eol=lf
*.bat text eol=crlf
*.png binary
*.c working-tree-encoding=UTF-16LE-BOM
Cloud Sync Service Hazard: Never store active Git repositories inside folders managed by cloud syncing services (e.g., iCloud, OneDrive, Dropbox). These background utilities synchronize files continuously without understanding Git's internal transactional locks. Syncing active database updates corrupts index structures, breaks commit references, and causes permanent data loss during garbage collection.
Emergency Disaster Recovery
If destructive resets or accidental branch deletions occur, Git's reference log (reflog) provides transactional recovery paths. The engine retains chronological records of every local pointer modification for 90 days.
# Display chronological log of all local HEAD pointer movements
git reflog
# Recover orphaned commit hash by generating a new branch pointing to the SHA target
git branch recovery-branch 8f7e6d5
# Undo last commit while preserving working directory edits safely on disk
git reset --soft HEAD~1
# Permanently purge untracked files and directories to restore pristine workspace
git clean -fd
References & Further Reading
- GitHub. Git Guides. Official Git documentation and interactive tutorials provided by the GitHub team.
- GitHub Education. Git Cheat Sheet (PDF). A printable, rapid-reference manual covering standard repository workflows and commands.
- GitLab. Common Git Commands. GitLab's structured documentation on everyday Git operations and architecture.
- Git SCM. Git Reference Manual. The official, exhaustive reference documentation for the Git version control engine.
- Krukowski, Ilya. 10 Git Commands for Your Day-to-Day Work. Lokalise Blog. Practical insights and detailed explanations for executing daily version control tasks.