Git Command Reference

Table of Contents


Core Concepts

Repository

A repository (repo) is a folder that Git is tracking. It contains: - Your project files - .git directory (Git's tracking database) - Commit history - Branch information

Commit

A commit is a snapshot of your project at a specific point in time. Each commit has: - Unique ID (SHA hash) - Description message - Author information - Timestamp - Parent commit(s)

Think of commits as save points in a video game - you can always go back to them.

Branch

A branch is a separate line of development. It allows you to: - Work on features independently - Keep main branch stable - Experiment without breaking production code

Default branch is typically main (formerly master).


Initial Setup

One-Time Configuration

# Set your name (appears in commits)
git config --global user.name "Your Name"

# Set your email (appears in commits)
git config --global user.email "your.email@gmail.com"

# Set default branch name to 'main'
git config --global init.defaultBranch main

# Set default editor (optional)
git config --global core.editor "code --wait"  # VS Code
git config --global core.editor "nano"         # Nano

# View all configurations
git config --list

# View specific configuration
git config user.name
git config user.email

Initialize a New Repository

# Create new Git repository in current folder
git init

# Create new Git repository in specific folder
git init project-name
cd project-name

This creates a .git directory that tracks all changes.


Basic Workflow

Check Status

# Show status of working directory
git status

# Short format (compact view)
git status -s

Status shows: - ✅ Staged files (ready to commit) - ⚠️ Modified files (not staged) - ❓ Untracked files (not in Git yet)

Add Files to Staging

# Add specific file
git add filename.txt

# Add all files in current directory
git add .

# Add all files in repository
git add --all
git add -A

# Add specific file types
git add *.py          # All Python files
git add src/*.js      # All JS files in src/

# Add files interactively (choose what to stage)
git add -p

Staging Area: Think of it as a "loading dock" where you prepare files before committing.

Commit Changes

# Commit staged files with message
git commit -m "Add user authentication feature"

# Commit with multi-line message
git commit -m "Add user authentication" -m "- Added login page
- Implemented JWT tokens
- Added password hashing"

# Add all changes and commit in one step
git commit -am "Update README"

# Open editor for detailed commit message
git commit

Good Commit Messages: - ✅ Add user login feature - ✅ Fix navigation bug on mobile - ✅ Update dependencies to latest versions - ❌ Updated stuff - ❌ Fixed bug - ❌ asdf

View History

# Show full commit history
git log

# Show one-line summary (compact)
git log --oneline

# Show last 5 commits
git log -5

# Show commits with file changes
git log --stat

# Show commits with actual changes
git log -p

# Show graph of branches
git log --graph --oneline --all

# Show commits by specific author
git log --author="John Doe"

# Show commits in date range
git log --since="2 weeks ago"
git log --until="2024-01-01"

Branching and Merging

Create and Switch Branches

# List all branches
git branch

# List all branches (including remote)
git branch -a

# Create new branch
git branch feature-login

# Switch to branch
git checkout feature-login

# Create and switch in one command
git checkout -b feature-login

# Modern alternative (Git 2.23+)
git switch feature-login
git switch -c feature-login  # Create and switch

Merge Branches

# Switch to branch you want to merge INTO
git checkout main

# Merge feature branch into current branch (main)
git merge feature-login

# Merge with message
git merge feature-login -m "Merge login feature"

# Abort merge if conflicts
git merge --abort

Merge Workflow Example:

# Create feature branch
git checkout -b feature-payment

# Work on feature... make commits
git add payment.py
git commit -m "Add payment processing"

# Switch back to main
git checkout main

# Merge feature into main
git merge feature-payment

# Delete feature branch (cleanup)
git branch -d feature-payment

Delete Branches

# Delete branch (safe - won't delete if unmerged)
git branch -d branch-name

# Force delete branch (even if unmerged)
git branch -D branch-name

# Delete remote branch
git push origin --delete branch-name

Working with GitHub

Clone Existing Repository

# Clone repository from GitHub
git clone https://github.com/username/repository.git

# Clone into specific folder
git clone https://github.com/username/repository.git my-folder

# Clone specific branch
git clone -b branch-name https://github.com/username/repository.git

Connect Local Repository to GitHub

# Add remote repository
git remote add origin https://github.com/username/repository.git

# View remote repositories
git remote -v

# Change remote URL
git remote set-url origin https://github.com/username/new-repo.git

# Remove remote
git remote remove origin

Push Changes to GitHub

# Push commits to GitHub (main branch)
git push origin main

# Push and set upstream (first time)
git push -u origin main

# Push all branches
git push --all origin

# Push with tags
git push --tags

First Push Example:

# Create repository on GitHub first, then:
git remote add origin https://github.com/username/project.git
git branch -M main
git push -u origin main

Fetch Changes from GitHub

# Download changes (doesn't merge)
git fetch origin

# Fetch all branches
git fetch --all

# Fetch and prune deleted remote branches
git fetch --prune

Fetch vs Pull: - Fetch: Downloads changes but doesn't merge (safe) - Pull: Downloads and merges automatically

Compare Changes

# See what changed on remote
git diff main origin/main

# See what files changed
git diff --name-only main origin/main

# Compare current branch with remote
git diff HEAD origin/main

Merge Downloaded Changes

# Merge remote changes into current branch
git merge origin/main

# Merge with custom message
git merge origin/main -m "Merge remote changes"

Pull Changes from GitHub

# Download and merge changes (main branch)
git pull origin main

# Pull with rebase (cleaner history)
git pull --rebase origin main

# Pull all branches
git pull --all

Pull = Fetch + Merge

# These are equivalent:
git pull origin main

# Is the same as:
git fetch origin
git merge origin/main

Advanced Commands

Undo Changes

# Discard changes in working directory
git checkout -- filename.txt

# Discard all changes
git checkout -- .

# Unstage file (keep changes)
git reset HEAD filename.txt

# Unstage all files
git reset HEAD

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

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

# Revert commit (creates new commit)
git revert commit-hash

Stash Changes

# Save changes temporarily
git stash

# Save with message
git stash save "Work in progress on login"

# List stashes
git stash list

# Apply most recent stash
git stash apply

# Apply and remove stash
git stash pop

# Apply specific stash
git stash apply stash@{0}

# Delete stash
git stash drop stash@{0}

# Clear all stashes
git stash clear

View Changes

# Show unstaged changes
git diff

# Show staged changes
git diff --staged
git diff --cached

# Show changes for specific file
git diff filename.txt

# Show changes between commits
git diff commit1 commit2

# Show changes between branches
git diff main feature-branch

Tags

# Create lightweight tag
git tag v1.0.0

# Create annotated tag (recommended)
git tag -a v1.0.0 -m "Release version 1.0.0"

# List tags
git tag

# Push tag to remote
git push origin v1.0.0

# Push all tags
git push --tags

# Delete tag
git tag -d v1.0.0

# Delete remote tag
git push origin --delete v1.0.0

Ignore Files

Create .gitignore file:

# Create .gitignore
touch .gitignore
nano .gitignore

Example .gitignore content:

# Python
__pycache__/
*.pyc
*.pyo
.env
venv/

# Node.js
node_modules/
npm-debug.log

# IDE
.vscode/
.idea/
*.swp

# OS
.DS_Store
Thumbs.db

# Build
dist/
build/
*.egg-info/

Common Workflows

Workflow 1: Starting New Project

# Create project folder
mkdir my-project
cd my-project

# Initialize Git
git init

# Create files
touch README.md
echo "# My Project" > README.md

# Add and commit
git add .
git commit -m "Initial commit"

# Connect to GitHub
git remote add origin https://github.com/username/my-project.git
git push -u origin main

Workflow 2: Daily Development

# Start of day: Get latest changes
git pull origin main

# Create feature branch
git checkout -b feature-new-ui

# Work on feature... make changes
git add .
git commit -m "Update UI design"

# Push feature branch
git push origin feature-new-ui

# Merge to main when ready
git checkout main
git merge feature-new-ui
git push origin main

# Delete feature branch
git branch -d feature-new-ui
git push origin --delete feature-new-ui

Workflow 3: Contributing to Open Source

# Fork repository on GitHub, then:

# Clone your fork
git clone https://github.com/your-username/project.git
cd project

# Add upstream remote (original repository)
git remote add upstream https://github.com/original-owner/project.git

# Create feature branch
git checkout -b fix-bug-123

# Make changes and commit
git add .
git commit -m "Fix bug #123"

# Push to your fork
git push origin fix-bug-123

# Create Pull Request on GitHub

# Keep fork updated
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

Workflow 4: Fixing Mistakes

# Oops, made changes to wrong branch
git stash                    # Save changes
git checkout correct-branch  # Switch to correct branch
git stash pop               # Apply changes

# Oops, committed to wrong branch
git reset --soft HEAD~1     # Undo commit (keep changes)
git stash                   # Save changes
git checkout correct-branch # Switch branch
git stash pop              # Apply changes
git add .
git commit -m "Correct commit"

# Oops, need to change last commit message
git commit --amend -m "New message"

# Oops, forgot to add file to last commit
git add forgotten-file.txt
git commit --amend --no-edit

Troubleshooting

Common Issues and Solutions

Merge Conflicts

# When merge conflict occurs:
# 1. Open conflicting files (look for <<<<<<< markers)
# 2. Resolve conflicts manually
# 3. Stage resolved files
git add conflicted-file.txt

# 4. Complete merge
git commit -m "Resolve merge conflict"

# Or abort merge
git merge --abort

Accidentally Committed to Wrong Branch

# Move last commit to new branch
git branch feature-branch
git reset --hard HEAD~1
git checkout feature-branch

Need to Undo Push

# Revert commit (safe - creates new commit)
git revert commit-hash
git push origin main

# Force push (dangerous - rewrites history)
git reset --hard HEAD~1
git push --force origin main  # Use with caution!

Detached HEAD State

# Save work from detached HEAD
git checkout -b new-branch-name

# Or discard and return to branch
git checkout main

Authentication Issues

# Use Personal Access Token (PAT) instead of password
# GitHub Settings → Developer Settings → Personal Access Tokens

# Cache credentials (1 hour)
git config --global credential.helper cache

# Cache credentials (custom time)
git config --global credential.helper 'cache --timeout=3600'

# Store credentials permanently (less secure)
git config --global credential.helper store

Quick Reference

Essential Commands

Command Purpose
git init Initialize repository
git status Check status
git add . Stage all changes
git commit -m "msg" Commit changes
git push origin main Push to GitHub
git pull origin main Pull from GitHub
git clone url Clone repository
git branch name Create branch
git checkout name Switch branch
git merge name Merge branch
git log --oneline View history

File States

State Description
Untracked New file, not in Git yet
Modified Changed file, not staged
Staged Ready to be committed
Committed Saved in Git history

Branch Commands

git branch                    # List branches
git branch new-branch         # Create branch
git checkout branch-name      # Switch branch
git checkout -b new-branch    # Create and switch
git merge branch-name         # Merge branch
git branch -d branch-name     # Delete branch

Remote Commands

git remote -v                 # View remotes
git remote add origin url     # Add remote
git push origin main          # Push to remote
git pull origin main          # Pull from remote
git fetch origin              # Download changes
git clone url                 # Clone repository

Git Aliases (Time Savers)

Add to ~/.gitconfig or use git config --global:

# Setup aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual 'log --graph --oneline --all'

# Usage:
git st              # Instead of git status
git co main         # Instead of git checkout main
git ci -m "msg"     # Instead of git commit -m "msg"
git visual          # Pretty branch graph

Best Practices

Commit Messages

Good practices: - Use imperative mood: "Add feature" not "Added feature" - Be specific: "Fix login button alignment" not "Fix bug" - Keep first line under 50 characters - Add details in body if needed

Branching Strategy

Feature Branch Workflow:

main (production)
  ├── feature-login
  ├── feature-payment
  └── bugfix-navbar

Git Flow:

main (production)
  └── develop (integration)
      ├── feature-x
      ├── feature-y
      └── hotfix-z

Do's and Don'ts

Do: - Commit often with meaningful messages - Pull before you push - Create branches for features - Review changes before committing - Keep commits atomic (one logical change)

Don't: - Commit sensitive data (passwords, API keys) - Force push to shared branches - Commit large binary files - Make huge commits with many unrelated changes - Work directly on main branch


Additional Resources

Happy version controlling! 🚀📝