# Git for Beginners: Basics and Essential Commands

## What is Git?

Git is version control software. It tracks changes to your code over time.

Remember the "pendrive problem"? Git solves that. Instead of `final_v2_`[`ACTUAL.zip`](http://ACTUAL.zip), you get a clean history of every change you've ever made.

Git is **distributed**, meaning everyone has a full copy of the project history on their computer. You're not dependent on one central server.

## Why Use Git?

**Track changes:** See what changed, when, and who changed it.

**Undo mistakes:** Made a bad change? Go back to any previous version.

**Work in parallel:** Multiple people can work on the same project without overwriting each other.

**Experiment safely:** Try new features in branches without breaking the main code.

**Collaborate:** Share code through platforms like GitHub.

Every professional developer uses Git. It's not optional.

## Core Concepts

Before jumping into commands, understand these terms:

**Repository (repo):** A folder that Git is tracking. Contains all your code and the complete history.

**Commit:** A snapshot of your code at a specific point in time. Think of it like a save point in a video game.

**Branch:** A separate line of development. The main branch is usually called `main` or `master`. You create new branches to work on features.

**HEAD:** A pointer to your current location (which commit and branch you're on).

**Working Directory:** The actual files you're editing.

**Staging Area:** A holding zone for changes before you commit them.

**Remote:** A version of your repository hosted somewhere else (like GitHub).

## How Git Works: The Three States

Your files live in three places:

```mermaid
graph LR
    A[Working Directory<br/>Files you're editing] -->|git add| B[Staging Area<br/>Changes ready to commit]
    B -->|git commit| C[Repository<br/>Permanent history]

    style A fill:#F59E0B,stroke:#B45309,color:#fff
    style B fill:#3B82F6,stroke:#1E40AF,color:#fff
    style C fill:#10B981,stroke:#047857,color:#fff
```

**1\. Working Directory:** You edit `index.html`

**2\. Staging Area:** You run `git add index.html` - Git now knows you want to save this change

**3\. Repository:** You run `git commit` - The change is permanently saved in Git's history

This two-step process (add then commit) gives you control over exactly what you save.

## Setting Up Git

First time using Git? Set your name and email:

```bash
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
```

Git will attach this info to every commit you make.

## Essential Commands

### Starting a New Project

**Create a new repository:**

```bash
mkdir my-project
cd my-project
git init
```

This creates a `.git` folder that stores all the history. Your folder is now a Git repository.

### Checking Status

**See what's changed:**

```bash
git status
```

This shows:

* Files you've modified
    
* Files in the staging area
    
* Files Git isn't tracking yet
    

You'll use `git status` constantly.

### Adding Files

**Add a file to staging:**

```bash
git add filename.txt
```

**Add all changed files:**

```bash
git add .
```

**Add specific files:**

```bash
git add file1.js file2.css
```

### Making Commits

**Commit staged changes:**

```bash
git commit -m "Add login feature"
```

The `-m` flag lets you write a commit message. Make it descriptive so you know what changed.

**Bad commit messages:**

```bash
git commit -m "update"
git commit -m "fix"
git commit -m "asdfasdf"
```

**Good commit messages:**

```bash
git commit -m "Fix login button not responding on mobile"
git commit -m "Add user authentication with JWT"
git commit -m "Remove deprecated API endpoints"
```

### Viewing History

**See all commits:**

```bash
git log
```

Shows commit history with messages, authors, and dates.

**Compact view:**

```bash
git log --oneline
```

Shows one line per commit. Much easier to read.

### Checking Differences

**See what changed:**

```bash
git diff
```

Shows exactly what lines you modified in your working directory.

**See staged changes:**

```bash
git diff --staged
```

## Basic Workflow

Here's what a typical workflow looks like:

```bash
# 1. Create a new file
echo "console.log('hello');" > app.js

# 2. Check status
git status
# Output: app.js is untracked

# 3. Add to staging
git add app.js

# 4. Check status again
git status
# Output: app.js is staged and ready to commit

# 5. Commit
git commit -m "Add initial app.js file"

# 6. View history
git log --oneline
```

```mermaid
graph TB
    A[Create/Edit Files] --> B[git status<br/>Check what changed]
    B --> C[git add<br/>Stage changes]
    C --> D[git commit<br/>Save snapshot]
    D --> E[git log<br/>View history]
    E -.-> A

    style A fill:#F59E0B,stroke:#B45309,color:#fff
    style B fill:#8B5CF6,stroke:#6D28D9,color:#fff
    style C fill:#3B82F6,stroke:#1E40AF,color:#fff
    style D fill:#10B981,stroke:#047857,color:#fff
    style E fill:#EC4899,stroke:#BE185D,color:#fff
```

## Working with Branches

Branches let you work on features without touching the main code.

**Create a new branch:**

```bash
git branch feature-login
```

**Switch to that branch:**

```bash
git checkout feature-login
```

**Create and switch in one command:**

```bash
git checkout -b feature-login
```

**See all branches:**

```bash
git branch
```

The branch with `*` is your current branch.

**Switch back to main:**

```bash
git checkout main
```

**Merge a branch:**

```bash
git checkout main
git merge feature-login
```

This brings all changes from `feature-login` into `main`.

## Working with Remote Repositories

A remote is a version of your repo on GitHub, GitLab, etc.

**Add a remote:**

```bash
git remote add origin https://github.com/username/repo.git
```

`origin` is just a nickname for that URL.

**Push your code to GitHub:**

```bash
git push origin main
```

Sends your `main` branch to GitHub.

**Pull changes from GitHub:**

```bash
git pull origin main
```

Downloads changes other people made.

**Clone an existing repo:**

```bash
git clone https://github.com/username/repo.git
```

Downloads the entire repo to your computer.

## Common Scenarios

### Scenario 1: Starting a New Project

```bash
# Create folder and initialize git
mkdir my-app
cd my-app
git init

# Create some files
echo "# My App" > README.md
echo "console.log('hello');" > app.js

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

# Connect to GitHub (create repo there first)
git remote add origin https://github.com/yourusername/my-app.git
git push -u origin main
```

### Scenario 2: Contributing to an Existing Project

```bash
# Clone the repo
git clone https://github.com/company/project.git
cd project

# Create a branch for your feature
git checkout -b add-dark-mode

# Make changes
# ... edit files ...

# Stage and commit
git add .
git commit -m "Add dark mode toggle"

# Push your branch
git push origin add-dark-mode

# Create pull request on GitHub
```

### Scenario 3: Daily Work Routine

```bash
# Start your day - get latest changes
git pull origin main

# Create branch for today's task
git checkout -b fix-header-bug

# Work on it
# ... make changes ...

# Save progress
git add .
git commit -m "Fix header alignment issue"

# Push to GitHub
git push origin fix-header-bug

# Create pull request for review
```

## Commit History Visualization

Here's what your commit history looks like:

```mermaid
graph LR
    A[Commit 1<br/>Initial commit] --> B[Commit 2<br/>Add login]
    B --> C[Commit 3<br/>Fix bug]
    C --> D[Commit 4<br/>Add logout]
    D --> E[HEAD<br/>Current position]

    style A fill:#6B7280,stroke:#4B5563,color:#fff
    style B fill:#6B7280,stroke:#4B5563,color:#fff
    style C fill:#6B7280,stroke:#4B5563,color:#fff
    style D fill:#6B7280,stroke:#4B5563,color:#fff
    style E fill:#10B981,stroke:#047857,color:#fff
```

Each commit points to the previous one, forming a chain. You can move backward to any commit.

## Undoing Things

**Undo changes in working directory:**

```bash
git checkout -- filename.txt
```

Discards changes you haven't committed yet.

**Unstage a file:**

```bash
git reset filename.txt
```

Moves file out of staging area but keeps your changes.

**Undo last commit (but keep changes):**

```bash
git reset --soft HEAD~1
```

Removes the commit but your changes are still there.

**Undo last commit (and discard changes):**

```bash
git reset --hard HEAD~1
```

Careful - this deletes your changes.

## Local Repository Structure

When you run `git init`, here's what you get:

```plaintext
my-project/
├── .git/                 # Git's internal folder (don't touch this)
│   ├── objects/         # All commits and file versions
│   ├── refs/            # Branch pointers
│   ├── HEAD             # Current branch pointer
│   └── config           # Repo configuration
├── app.js               # Your actual code files
├── index.html
└── style.css
```

Everything Git needs is in `.git/`. Your working directory has the actual files you edit.

## Quick Command Reference

| Command | What It Does |
| --- | --- |
| `git init` | Create new repo |
| `git status` | Check what's changed |
| `git add <file>` | Stage a file |
| `git add .` | Stage all changes |
| `git commit -m "message"` | Save a snapshot |
| `git log` | View commit history |
| `git log --oneline` | Compact history |
| `git diff` | See changes |
| `git branch` | List branches |
| `git branch <name>` | Create branch |
| `git checkout <branch>` | Switch branch |
| `git checkout -b <name>` | Create and switch |
| `git merge <branch>` | Merge branch |
| `git pull` | Download changes |
| `git push` | Upload changes |
| `git clone <url>` | Copy a repo |

## Tips for Beginners

**Commit often:** Don't wait until you've changed 50 files. Commit each logical change.

**Write clear messages:** Your future self will thank you.

**Use branches:** Don't work directly on `main`. Create branches for features.

**Pull before you push:** Always get the latest changes before uploading yours.

**Check status:** Use `git status` constantly to know where you are.

**Don't panic:** Made a mistake? Git can almost always undo it.

## Common Mistakes

**Committing without staging:**

```bash
# This won't work
git commit -m "changes"  # Nothing happens if you didn't git add first
```

**Forgetting to pull:**

```bash
# You push without pulling first
git push
# Error: Updates were rejected because remote has changes you don't have
```

**Working on main instead of a branch:** Bad habit. Always create a branch for new work.

**Commit messages like "update":** Six months from now, you won't remember what "update" means.

**Not committing frequently enough:** If your commit message needs three paragraphs to explain what changed, you waited too long.

## What's Next?

You now know the basics:

* Initialize repos
    
* Stage and commit changes
    
* View history
    
* Work with branches
    
* Push/pull from GitHub
    

**Next steps to learn:**

* Resolving merge conflicts
    
* Rebasing
    
* Stashing changes
    
* Cherry-picking commits
    
* Advanced branching strategies
    

But honestly, these basics will cover 90% of your daily Git usage. The rest you'll learn as you need it.

Start using Git for your projects now. Real practice is the only way to get comfortable with it.

---
