Skip to content

Latest commit

 

History

History
402 lines (300 loc) · 11.5 KB

git-cli-tutorial.md

File metadata and controls

402 lines (300 loc) · 11.5 KB

Comprehensive Git Command-Line (CLI) Tutorial (Windows & macOS)

A practical, visual guide to mastering Git in your terminal on both Windows and macOS. Learn platform installation, terminal setups, line-ending configurations, the core mental model, everyday commands, branching strategies, stashing, and conflict resolution.


Table of Contents

  1. Platform Installation (Windows & macOS)
  2. Terminal Selection & Cross-Platform Configuration
  3. Git Architecture: The 4 Fundamental Areas
  4. Creating & Cloning Repositories
  5. The Daily Developer Workflow
  6. Branching & Merging
  7. Stashing Changes (Temporary Shelving)
  8. Undoing Mistakes & Fixing Errors
  9. Resolving Merge Conflicts
  10. Cross-Platform .gitignore & Best Practices

1. Platform Installation (Windows & macOS)

🪟 Windows Installation

You have two easy ways to install Git on Windows:

Option A: Official GUI Installer (Recommended for Beginners)

  1. Visit git-scm.com/download/win and download the 64-bit installer for Windows.
  2. Run the .exe installer.
  3. During setup, keep the recommended defaults:
    • Text Editor: Choose your preferred editor (VS Code, Notepad++, etc.).
    • Default branch name: Choose main.
    • Adjusting your PATH: Select "Git from the command line and also from 3rd-party software".
    • Line ending conversion: Choose "Checkout Windows-style, commit Unix-style line endings".
    • Credential Helper: Choose "Git Credential Manager".
  4. Finish installation. You now have Git Bash, Git GUI, and command-line Git available.

Option B: Windows Package Manager (Winget)

Open PowerShell or Windows Terminal as Administrator and run:

winget install --id Git.Git -e --source winget

🍎 macOS Installation

Option A: Xcode Command Line Tools (No Package Manager Required)

macOS comes with a stub that can install Git automatically. Open Terminal.app (Press Cmd + Space, type Terminal, and hit Enter), then run:

xcode-select --install

Click Install in the software update popup and accept the license.

Option B: Homebrew (Recommended for Developers)

If you use Homebrew, install the most up-to-date Git package:

brew install git

Verify Installation on Either Platform

Open your terminal (Git Bash or PowerShell on Windows, Terminal on macOS) and run:

git --version
# Expected output: git version 2.x.x

2. Terminal Selection & Cross-Platform Configuration

Choosing the Right Terminal

Platform Recommended Shell Description
Windows Git Bash (Top Pick) Emulates a Unix environment inside Windows. Lets you use standard Linux commands (ls, pwd, mkdir, rm, cat) identically to macOS.
Windows PowerShell / Windows Terminal Modern native Windows shell. Fully supports git, but uses Windows-specific flags and cmdlets.
macOS Terminal.app / iTerm2 Built-in macOS shell powered by zsh. Fast, robust, and natively Unix.

Handy Terminal Commands Comparison

Action Windows (CMD / PowerShell) macOS / Git Bash
List files dir / Get-ChildItem ls -la
Print working folder cd / pwd pwd
Clear screen cls clear or Cmd + K
Copy / Paste Ctrl + C / Ctrl + V Cmd + C / Cmd + V (macOS) or Ctrl + Shift + V (Git Bash)

Critical Configuration: Line Endings (CRLF vs LF)

Warning

Windows uses Carriage Return + Line Feed (CRLF / \r\n) to represent new lines, while macOS and Linux use Line Feed (LF / \n). If left unconfigured, Git may treat entire files as modified when team members collaborate across Windows and macOS!

Configure Git to handle line endings automatically according to your operating system:

On Windows:

git config --global core.autocrlf true

(Converts LF to CRLF when checking out code, and converts CRLF back to LF when committing).

On macOS:

git config --global core.autocrlf input

(Leaves LF unchanged on checkout, and ensures any accidental CRLF is converted to LF upon commit).


User Profile & Authentication Setup

Run these commands on both Windows and macOS:

# Set your name and email (must match your GitHub account)
git config --global user.name "Your Full Name"
git config --global user.email "your.email@example.com"

# Set the modern default branch name
git config --global init.defaultBranch main

# Enable colored terminal output
git config --global color.ui auto

Credential Helpers (Remembering Your Login)

  • Windows: Git for Windows automatically configures Git Credential Manager to safely store your credentials in the Windows Credential Manager.
  • macOS: Configure Git to use the native macOS Keychain:
    git config --global credential.helper osxkeychain

3. Git Architecture: The 4 Fundamental Areas

Regardless of your operating system, Git manages code through four distinct states:

Git Architecture and 4 Fundamental Areas

  1. Working Directory (Local Workspace): The active files on your local drive (C:\... on Windows or /Users/... on macOS).
  2. Staging Area (Index / Cache): The preparation area where you organize files before recording a snapshot.
  3. Local Repository (.git database): The local history on your computer. Every commit is a permanent snapshot identified by a SHA-1 hash.
  4. Remote Repository (GitHub / GitLab): The cloud-hosted copy shared with your team.

4. Creating & Cloning Repositories

Initializing a New Local Project

On Windows:

# In Git Bash:
cd /c/Users/YourUsername/Projects/my-app
git init

# Or in PowerShell:
cd C:\Users\YourUsername\Projects\my-app
git init

On macOS:

cd ~/Projects/my-app
git init

Cloning an Existing Remote Repository

Works identically on both Windows and macOS:

# Clone via HTTPS
git clone https://github.com/username/repository-name.git

# Or clone via SSH (if SSH keys are installed)
git clone git@github.com:username/repository-name.git

# Move into the cloned project folder
cd repository-name

5. The Daily Developer Workflow

The day-to-day cycle is identical across platforms: check status, stage modifications, commit, and push.

Daily Git Terminal Workflow

Step 1: Check Repository Status

Always check what has changed:

git status

Step 2: Stage Files (git add)

Choose which files to include in your next commit:

# Stage a specific file
git add src/index.js

# Stage multiple specific files
git add src/index.js src/styles.css

# Stage all modified and untracked files
git add .

Step 3: Commit Changes (git commit)

Record a snapshot with a meaningful description:

git commit -m "feat: implement responsive navigation bar"

Step 4: Synchronize (git pull & git push)

Download team changes and upload your commits to GitHub:

# Download latest commits from GitHub
git pull origin main

# Upload your new commits to GitHub
git push origin main

6. Branching & Merging

Isolate your work from the production main branch to avoid breaking stable code:

Git Branching and Merging Workflow

Everyday Branch Commands:

# List local branches (* denotes your current active branch)
git branch

# Create and switch to a new feature branch (modern syntax)
git switch -c feature/user-profile

# (Classic equivalent: git checkout -b feature/user-profile)

# Switch back to the main branch
git switch main

Merging a Feature Branch into Main:

# 1. Switch to main
git switch main

# 2. Update main with remote changes
git pull origin main

# 3. Merge feature branch into main
git merge feature/user-profile

# 4. Push updated main to GitHub
git push origin main

# 5. Delete the feature branch once safely merged
git branch -d feature/user-profile

7. Stashing Changes (Temporary Shelving)

Need to switch branches or pull a hotfix without committing half-finished work? Use git stash:

Git Stash Workflow

# Shelve all current uncommitted modifications
git stash

# Shelve including any new untracked files
git stash -u

# Inspect your stash list
git stash list

# Re-apply stashed work and remove it from the stash stack
git stash pop

# Discard the most recent stash
git stash drop

8. Undoing Mistakes & Fixing Errors

Discard Local Uncommitted Changes (Working Directory)

# Revert a single file back to the last commit
git restore src/app.js

# Revert ALL modified files in the working directory
git restore .

Unstage a File (Without losing your edits)

git restore --staged src/app.js

Amend the Last Commit (Fix typo or add forgotten file)

git add forgotten-file.js
git commit --amend -m "feat: complete user profile page"

Safely Undo a Commit Already Pushed to GitHub

# Creates a new inverted commit without rewriting public history
git revert <commit-hash>

9. Resolving Merge Conflicts

A merge conflict happens when two teammates edit the exact same lines of the same file on different branches:

Merge Conflict Resolution Guide

Step-by-Step Resolution:

  1. Run git status to identify conflicting files under Unmerged paths.
  2. Open the file in your code editor (VS Code highlights conflicts with buttons: Accept Current Change, Accept Incoming Change, or Accept Both).
  3. If editing manually, locate the conflict markers:
    <<<<<<< HEAD (Current branch code)
    const API_BASE = "https://api.myapp.com";
    =======
    const API_BASE = "https://api-v2.myapp.com";
    >>>>>>> feature/api-upgrade (Incoming branch code)
    
  4. Choose the correct code and delete all markers (<<<<<<<, =======, >>>>>>>).
  5. Stage the resolved file:
    git add src/config.js
  6. Finalize the merge commit:
    git commit -m "fix: resolve API_BASE URL merge conflict"

10. Cross-Platform .gitignore & Best Practices

When working in mixed Windows and macOS teams, always add platform-specific operating system artifacts to your .gitignore:

# ========================
# macOS System Junk
# ========================
.DS_Store
.AppleDouble
.LSOverride
._*
.Spotlight-V100
.Trashes

# ========================
# Windows System Junk
# ========================
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
Desktop.ini
$RECYCLE.BIN/

# ========================
# Development & Dependencies
# ========================
node_modules/
dist/
build/
.env
*.log

# ========================
# Code Editors
# ========================
.vscode/
.idea/
*.suo
*.user

Path Separator Tip for Windows Users

In Git commands and .gitignore, always use forward slashes (/), even on Windows. Git understands forward slashes natively across all platforms (e.g., git add src/components/Header.jsx).