Git Cheat Sheet - Intermediate

Pro Tip: Use git help <command> to get detailed help for any git command.

Basic Setup

Configure User

# Set global username and email
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Verify settings
git config --global --get user.name
git config --global --get user.email

Initialize Repository

# Create new repository
git init

# Clone existing repository
git clone <repository-url>

Basic Workflow

Stage Changes

# Stage all changes
git add .

# Stage specific file
git add <filename>

# Stage parts of a file
git add -p

Committing

# Commit with message
git commit -m "Your commit message"

# Stage and commit in one step
git commit -am "Your message"

# Amend last commit
git commit --amend

Branching & Merging

Branches

# List branches
git branch

# Create new branch
git branch <branch-name>

# Switch to branch
git checkout <branch-name>

# Create and switch to new branch
git checkout -b <branch-name>

Merging

# Merge branch into current branch
git merge <branch-name>

# Abort merge
git merge --abort

# Rebase current branch
git rebase <branch-name>

Viewing History & Changes

Log & History

# View commit history
git log

# One-line log
git log --oneline

# Graph view
git log --graph --oneline --all

# Show changes
git show <commit-hash>

Diffs

# Show unstaged changes
git diff

# Show staged changes
git diff --staged

# Compare branches
git diff branch1..branch2

Undoing Things

Undo Changes

# Discard changes in working directory
git restore <file>

# Unstage file
git restore --staged <file>

# Reset to specific commit
git reset --hard <commit-hash>

Stashing

# Stash changes
git stash

# List stashes
git stash list

# Apply last stash
git stash apply

# Drop stash
git stash drop

Remote Repositories

Working with Remotes

# Add remote
git remote add <name> <url>

# List remotes
git remote -v

# Fetch changes
git fetch <remote>

# Pull changes
git pull <remote> <branch>

# Push changes
git push <remote> <branch>
Remember: Always pull before you push to avoid conflicts!