Complete Git Commands Guide 2025: Essential Version Control for Developers
 
 Quick Answer
Essential Git commands for 2025 include: git switch for branch switching, git restore for file restoration, git stash for temporary changes, git pull for updates, git push for publishing, and git merge for combining branches. Modern Git recommends using switch instead of checkout for branches.
Git Initial Setup
First-Time Configuration
# Set user information
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
# Initialize repository
git init
# View configuration
git config --listUseful Settings
# Set default editor
git config --global core.editor "code --wait"
# Set aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commitFile Management
Basic Operations
# Check status
git status
git status -s          # Short format
# Add files
git add filename.txt
git add .              # Add all files
git add *.js           # Add all JS files
# Remove from staging
git reset filename.txt
git reset              # Remove all from stagingFile Operations
# Rename files
git mv oldname.txt newname.txt
# Delete files
git rm filename.txt
git rm --cached filename.txt    # Remove from Git only
# View differences
git diff                        # Working tree vs staging
git diff --staged              # Staging vs committedCommit Management
Commit Operations
# Commit changes
git commit -m "Commit message"
git commit -am "Quick commit"       # add + commit
# Modify last commit
git commit --amend -m "New message"
git commit --amend --no-edit    # Don't change message
# View history
git log
git log --oneline              # One line display
git log --graph                # Graphical view
git log --stat                 # Show statisticsRestore Operations
# Restore files
git restore filename.txt       # Recommended
git checkout filename.txt       # Legacy version
# Reset commits
git reset --soft HEAD~1        # Keep in staging area
git reset --mixed HEAD~1       # Keep in working tree
git reset --hard HEAD~1        # Delete completely
# Revert commits
git revert commit-hashBranch Operations
Branch Management
# View branches
git branch
git branch -a                  # Include remote branches
git branch -r                  # Remote branches only
# Create branches
git branch branch-name
git switch -c branch-name      # Recommended
git checkout -b branch-name    # Legacy version
# Switch branches
git switch branch-name         # Recommended (Git 2.23+)
git checkout branch-name       # Legacy but widely used
# Delete branches
git branch -d branch-name      # Safe delete
git branch -D branch-name      # Force deleteMerge Operations
# Merge branches
git merge branch-name
git merge --no-ff branch-name  # Preserve merge record
# Rebase
git rebase branch-name
git rebase -i HEAD~3           # Interactive rebase
# Cancel operations
git merge --abort
git rebase --abortRemote Operations
Remote Management
# Add remote
git remote add origin https://github.com/user/repo.git
# View remotes
git remote -v
git remote show origin
# Push changes
git push origin main
git push -u origin main        # Set upstream tracking
git push --all                 # Push all branches
# Pull changes
git pull
git pull origin main
git fetch                      # Download only, don't merge
git fetch --all                # Fetch all remotesCollaboration Operations
# Clone repository
git clone https://github.com/user/repo.git
git clone --depth 1 url        # Shallow clone
# Sync updates - Important: Choose correct strategy
git pull                       # Default: fetch + merge (creates merge commit)
git pull --rebase              # fetch + rebase (linear history)
git fetch upstream
git merge upstream/main
# Prune remote branches
git remote prune origin
git fetch --prunegit pull vs git pull —rebase
git pull (default behavior):
- Creates merge commits in history
- Safer for shared/published branches
- Preserves exact collaboration timeline
- May create “messy” non-linear history
git pull —rebase:
- Creates clean linear history
- Dangerous: Never use on published commits
- Suitable for personal feature branches
- May cause conflicts requiring manual resolution
Best practice: Only use git pull --rebase on unpublished local branches.
git pull —rebase Safety Guide
Safe usage conditions (all must be met):
- Feature branch: Not main or develop public branches
- Local commits: Your commits haven’t been pulled or depended on by others
- Personal work: No other developers collaborating on this branch
Dangerous scenarios (absolutely forbidden):
- Using on main, develop, or other public branches
- Commits already pulled by team members
- Multi-developer feature branches
- Commits already pushed and depended on by CI/CD or other systems
Critical Rebase Safety Rules
git pull —rebase safe scenarios:
# Personal feature branch, never pushed
git checkout -b feature/my-work
# Work only locally
git pull --rebase origin main
# Feature branch pushed but no one else depends on it
git push -u origin feature/my-work
# If no collaborators, still safe to rebase
git pull --rebase origin mainDangerous scenarios (never rebase):
# Main/shared branches
git checkout main
git pull --rebase  # Never do this
# Commits already pulled by teammates
git checkout feature/shared-work
git pull --rebase  # Will break teammates' history
# Commits already in PR/MR
# Once commits enter a Pull Request, don't rebaseReal consequences: If you rebase published commits, teammates will see:
- Git history conflicts
- “Your branch has diverged from origin/main” errors
- Need to force push their own work (also breaks others)
Teammate recovery after shared branch is incorrectly rebased:
# If main branch was incorrectly rebased
git fetch origin
git reset --hard origin/main
# May lose local work - backup first!Stash Management
Stash Operations
# Stash changes
git stash
git stash push -m "Stash message"
git stash -u                   # Include untracked files
# Manage stashes
git stash list
git stash show stash@{0}
# Restore stashes
git stash pop                  # Restore and delete
git stash apply stash@{0}      # Restore only, don't delete
# Clean stashes
git stash drop stash@{0}
git stash clear                # Clear allTag Management
Tag Operations
# Create tags
git tag v1.0.0
git tag -a v1.0.0 -m "Version 1.0.0"
# View tags
git tag
git tag -l "v1.*"
git show v1.0.0
# Push tags
git push origin v1.0.0
git push --tags
# Delete tags
git tag -d v1.0.0
git push origin :refs/tags/v1.0.0Professional Tagging & Release Management
Professional Tagging Strategy
Semantic Versioning (Recommended):
# Version format: MAJOR.MINOR.PATCH
git tag v1.0.0          # Initial release
git tag v1.0.1          # Bug fixes
git tag v1.1.0          # New features
git tag v2.0.0          # Breaking changes
# Annotated tags with release notes
git tag -a v1.2.0 -m "Release v1.2.0
Features:
- User authentication system
- 30% performance improvement
Bug fixes:
- Fix memory leak in data processing
- Resolve CSS layout issues"CI/CD Integration:
# Trigger automated deployment
git tag v1.0.0
git push origin v1.0.0
# List tags sorted by version
git tag -l --sort=-version:refnameProduction Release Workflow
Complete release process:
# 1. Prepare release branch
git checkout main
git pull origin main
git checkout -b release/v1.2.0
# 2. Update version files
echo "1.2.0" > VERSION
git add VERSION package.json  # Update version in related files
git commit -m "Bump version to 1.2.0"
# 3. Create and push tag
git tag -a v1.2.0 -m "Release v1.2.0
New Features:
- User authentication system
- Dashboard analytics
- Mobile responsive design
Bug Fixes:
- Fix memory leak in data processing
- Resolve Safari CSS layout issues
Breaking Changes:
- API endpoint /old-api deprecated
- Requires Node.js 18+"
# 4. Push everything
git push origin release/v1.2.0
git push origin v1.2.0
# 5. Merge back to main
git checkout main
git merge release/v1.2.0
git push origin main
# 6. Deploy (triggered by CI/CD on tag)
# GitHub Actions, GitLab CI, Jenkins will see the tagCI/CD Integration Example (GitHub Actions):
# .github/workflows/release.yml
name: Release
on:
  push:
    tags:
      - 'v*'
jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Extract version
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
      - name: Build and deploy
        run: |
          npm ci
          npm run build
          npm run deployHotfix release process:
# Production hotfix
git checkout tags/v1.2.0
git checkout -b hotfix/v1.2.1
# Fix critical issue
git add .
git commit -m "Fix critical security vulnerability"
# Tag hotfix
git tag -a v1.2.1 -m "Hotfix v1.2.1 - Security patch"
git push origin v1.2.1
# Merge back to main and develop
git checkout main
git merge hotfix/v1.2.1
git push origin mainSearch and Discovery
Content Search
# Search content
git grep "search string"
git grep -n "search string"         # Show line numbers
# Search history
git log --grep="keyword"
git log --author="author"
git log -S "code string"             # Search code changes
# View file history
git log filename.txt
git log -p filename.txt              # Show change content
git blame filename.txt               # Show author per lineDebugging Tools
# Binary search
git bisect start
git bisect good commit-hash
git bisect bad commit-hash
# View reference history
git reflog
git reflog expire --expire=now --allMaintenance and Cleanup
Cleanup Operations
# Clean untracked files
git clean -n                   # Preview
git clean -f                   # Clean files
git clean -fd                  # Clean files and directories
# Garbage collection
git gc
git gc --aggressive            # Aggressive cleanup
# Check integrity
git fsck
git fsck --fullConfiguration Management
# Ignore file changes
git update-index --skip-worktree filename.txt
git update-index --no-skip-worktree filename.txt
# Change remote URL
git remote set-url origin new-url
# Rewrite history (dangerous)
git filter-branch --env-filter 'export GIT_AUTHOR_EMAIL="[email protected]"'Workflows
Standard Flow
# Feature development flow
git switch main
git pull origin main
git switch -c feature/new-feature
# Development complete
git add .
git commit -m "Complete new feature"
git push -u origin feature/new-feature
# Merge and cleanup
git switch main
git pull origin main
git merge feature/new-feature
git branch -d feature/new-feature
git push origin mainConflict Resolution
# View conflicts
git status
git diff
git diff --ours              # Your changes
git diff --theirs            # Their changes
# After resolving conflicts
git add resolved-files
git commit
# Or abort merge
git merge --abortAdvanced Conflict Management
Advanced Conflict Resolution
Prevention strategies:
# Frequent syncing to avoid large conflicts
git fetch origin
git diff origin/main         # Check differences before merging
git merge --no-commit origin/main  # Preview merge without committingConflict Prevention in Team Workflows
1. Small, frequent branches:
# Good: Small, focused changes
git checkout -b feature/fix-login-button
# Make 1-3 related changes
git push origin feature/fix-login-button
# Bad: Large, long-lived branches
git checkout -b feature/complete-redesign
# Work for weeks without syncing2. Regular main branch syncing:
# Daily routine for feature branches
git checkout feature/my-work
git fetch origin
git merge origin/main         # or rebase when safe
git push origin feature/my-work
# This keeps your branch close to main, reducing conflicts3. Pull Request best practices:
# Before creating PR, ensure it's up to date
git checkout feature/my-work
git fetch origin
git merge origin/main
git push origin feature/my-work
# Now create PR - much less likely to have conflicts4. Team communication protocols:
- Announce major refactors - Warn team of potential conflicts
- Coordinate shared file changes - Discuss who changes what when
- Use feature flags - Avoid large merge conflicts in releases
- Split large features into smaller independent PRs
Conflict resolution tools:
# Set merge tool (one-time setup)
git config --global merge.tool vimdiff
git config --global merge.tool code
# Use merge tool for conflicts
git mergetool
# View file history for context
git log --oneline -- filename.txt
git blame filename.txtConflicts during rebase:
# Continue after fixing conflicts
git add resolved-files
git rebase --continue
# Skip problematic commit
git rebase --skip
# Abort entire rebase
git rebase --abortEmergency Recovery
Common Issues
# Undo git add
git reset HEAD filename.txt
# Recover deleted commits
git reflog
git cherry-pick commit-hash
# Complete reset
git fetch origin
git reset --hard origin/main
# Force push (use carefully)
git push --force-with-leaseForce Push: The Nuclear Option
Understanding force push:
git push --force              # Nuclear: completely overwrite remote
git push --force-with-lease   # Safer: check for conflicts first
git push --force-if-includes  # Safest: more protection checksReal force push scenario:
# Your feature branch has commits A-B-C
# You do rebase to clean history
git rebase -i HEAD~3
# Now you have A'-B'-C' (different commit hashes)
# Normal push will fail
git push  # Error: Updates were rejected
# Solution: force push (carefully!)
git push --force-with-lease origin feature/my-branchForce Push Real Disaster Scenarios
If you use --force on a shared branch, teammates will experience:
Step 1: Disaster strikes
# You force push on the shared feature/login branch
git push --force origin feature/loginStep 2: Teammate Alice’s experience
# Alice tries to push her work
git push origin feature/login
# Error: ! [rejected] feature/login -> feature/login (non-fast-forward)
# Alice tries to pull
git pull origin feature/login
# Error: Your branch and 'origin/feature/login' have diverged,
# and have 2 and 3 different commits each, respectively.Step 3: Alice sees the chaos
git log --oneline --graph
# * abc123 (HEAD -> feature/login) Alice's work
# * def456 Alice's previous work
# | * 789xyz (origin/feature/login) Your new history after force push
# | * 456abc Your rewritten commits
# |/
# * 123def Common ancestorStep 4: Teammate’s painful recovery process
# Alice's correct recovery (complex and error-prone):
git fetch origin
git branch backup-alice-work    # Backup her work first!
# Option 1: Reapply work (recommended)
git reset --hard origin/feature/login
git cherry-pick backup-alice-work~1..backup-alice-work
# Option 2: Merge conflicts (can be very complex)
git merge origin/feature/login  # Will have many conflicts
# Alice now must also force push (chain reaction)
git push --force-with-lease origin feature/loginReal consequence statistics:
- A 3-person team branch gets force pushed
- Each person spends 30-60 minutes recovering work
- Potential loss of 2-4 hours of development progress
- An emergency team meeting needed to discuss history reconstruction
- CI/CD pipelines may break or produce incorrect builds
Safe force push protocol:
- Communicate first - Notify team before force pushing
- Use —force-with-lease - Prevents overwriting others’ work
- Feature branches only - Never on main/shared branches
- Confirm no collaborators - Check branch has no other people’s commits
- Backup important work - Create a branch before dangerous operations
Dangerous Operations - Read Before Using
History rewriting commands (never use on shared branches):
# These commands rewrite history - extremely dangerous in team environments
git rebase -i HEAD~3          # Interactive rebase
git reset --hard HEAD~1       # Permanent deletion
git push --force              # Dangerous: overwrites remote
git push --force-with-lease   # Safer: checks for conflicts firstCritical warnings:
- Never rebase published/shared commits - Will break others’ work
- Never use —force without —with-lease - May destroy others’ work
- Always backup important work before dangerous operations
- Communicate with the team before any history-changing operations
Safe alternatives:
# Use merge instead of rebase on shared branches
git merge feature-branch
# Use revert instead of hard reset to preserve history
git revert commit-hash
# Create a new branch when using --force
git checkout -b fix-branchFix Issues
# Fix detached HEAD
git switch main
# Fix corrupted index
git reset --mixed HEAD
# Rebuild index
rm .git/index
git resetGit Command Quick Reference
Basic Operations
git status                      # Check current status
git add .                       # Add all changes
git commit -m "message"         # Commit changes
git push origin main            # Push to remote
git pull                        # Pull updatesBranch Management
git branch                      # View branches
git switch -c branch-name       # Create and switch branch
git merge branch-name           # Merge branch
git branch -d branch-name       # Delete branchRestore Operations
git reset HEAD filename.txt     # Unstage file
git restore filename.txt        # Restore file
git reset --hard HEAD~1         # Force rollback
git stash                       # Stash changesInformation Commands
git log --oneline               # Concise history
git diff                        # View differences
git blame filename.txt          # Line-by-line authors
git remote -v                   # View remotesGit Version Compatibility & Legacy Commands
Command Version Requirements
Modern commands (Git 2.23+):
git switch branch-name         # Git 2.23 (2019) introduced
git restore filename.txt       # Git 2.23 (2019) introducedLegacy commands (still valid):
git checkout branch-name       # Works on all Git versions
git checkout filename.txt      # Works on all Git versionsWhen to use legacy commands:
- Git version < 2.23: Some default environments haven’t updated to support switch/restore
- CI/CD systems: Many automated scripts still rely on checkout commands
- IDEs and tools: Some development tools internally still use checkout
- Team standards: Projects may require legacy commands for consistency
When to Use Legacy Commands
git checkout is not deprecated, still needed for:
# Check out specific commits (detached HEAD) - switch can't do this
git checkout commit-hash
git checkout HEAD~2
git checkout tags/v1.0.0
# Check out files from specific commits - restore has limitations here
git checkout commit-hash -- filename.txt
git checkout HEAD~3 -- src/config.js
# Create branch from specific commit
git checkout -b new-branch commit-hash
git checkout -b hotfix tags/v1.0.0
# Sparse checkout (advanced feature)
git checkout --sparse-checkout
# Legacy CI/CD systems and scripts
# Some IDEs and Git tools internally still use checkoutCommand Capability Comparison
| Operation | checkout | switch | restore | 
|---|---|---|---|
| Switch branches | ✓ | ✓ | ✗ | 
| Create branches | ✓ | ✓ | ✗ | 
| Detached HEAD | ✓ | ✗ | ✗ | 
| Restore work files | ✓ | ✗ | ✓ | 
| Restore from commit | ✓ | ✗ | ✓ | 
| Restore staged files | ✓ | ✗ | ✓ | 
| Complex scenarios | ✓ | Limited | Limited | 
When you must use checkout:
- Git version < 2.23 (switch/restore not available)
- Checking out specific commits for exploration
- Complex file restoration from arbitrary commits
- Legacy scripts not yet updated
- IDEs/tools not yet migrated to new commands
Best Practice Strategy
New projects (Git 2.23+):
- Use git switchfor branch operations
- Use git restorefor file operations
- Learn git checkoutfor advanced scenarios
Legacy systems:
- Stick with git checkoutwhen Git version < 2.23
- Check Git version: git --version
Team environments:
- Establish team conventions
- Document which commands to use
- Consider lowest common denominator approach
Check Your Git Version
# Check current Git version
git --version
# Update Git (system dependent)
# macOS with Homebrew: brew update && brew upgrade git
# Ubuntu/Debian: sudo apt update && sudo apt upgrade git
# Windows: Download from git-scm.comMinimum recommended versions:
- Git 2.23+ (for switch/restore commands)
- Git 2.17+ (for most modern features)
- Git 2.0+ (for basic professional use)
 
  
  
 