# Essential Git Commands

From Modern Git Academy — https://moderngitacademy.com/

Every command here has been run. Where a command is destructive, that is stated.

---

## Inspecting state

| Command | What it does |
| --- | --- |
| `git status --short --branch` | Compact view of staged, modified and untracked files |
| `git diff` | Changes in the working tree, not yet staged |
| `git diff --staged` | Exactly what the next commit will contain |
| `git log --oneline --graph --decorate --all` | Compact history with branch topology |
| `git show <ref>` | A commit's message and full diff |

**Read `git diff --staged` before every commit.** Most bad commits are prevented by this one habit.

## Staging

| Command | What it does |
| --- | --- |
| `git add <path>` | Copy current file content into the index |
| `git add -p` | Stage selected hunks interactively |
| `git restore --staged <path>` | Unstage, keeping your edits |

The index holds a snapshot from when you ran `git add`. Editing afterwards leaves the newer
content unstaged — this surprises people constantly.

## Committing

| Command | What it does |
| --- | --- |
| `git commit -m "<message>"` | Record the staged snapshot |
| `git commit --amend --no-edit` | Replace the last commit, keeping its message |
| `git commit -S -m "<message>"` | Create a signed commit |

⚠️ `--amend` creates a *different* commit with a different SHA. Amending anything already
pushed and shared requires a force push and coordination.

## Branches

| Command | What it does |
| --- | --- |
| `git switch -c <branch>` | Create a branch and move onto it |
| `git switch -` | Return to the previous branch |
| `git branch -vv` | Branches with upstream and ahead/behind counts |
| `git branch -d <branch>` | Delete a merged branch |

## Remotes

| Command | What it does |
| --- | --- |
| `git fetch --all --prune` | Update remote-tracking refs, drop stale ones |
| `git pull --rebase` | Fetch and replay your commits on top |
| `git push -u origin <branch>` | Push and set upstream tracking |
| `git push --force-with-lease` | Force push that refuses to clobber unseen commits |

⚠️ **Always prefer `--force-with-lease` to `--force`.** Plain `--force` will discard a
colleague's commits that landed while you were rebasing.

`git fetch` is always safe: it changes no local branch and no working tree file.

## Finding things

| Command | What it does |
| --- | --- |
| `git log -S"<string>"` | Commits that changed occurrences of a string |
| `git blame -L 40,60 <file>` | Which commit last touched each line |
| `git bisect start` | Binary-search history for the commit that broke something |

`git log -S` answers "when was this introduced or removed?" — often faster than blame.

---

Learn the model behind these: https://moderngitacademy.com/git/
