Complete Git Commands

Git is the most widely used distributed version control system (DVCS) in the world, created by Linus Torvalds in 2005 to manage the Linux kernel source code. This is an exhaustive reference covering every major Git command, workflow, and internal concept — from your first git init to advanced plumbing commands used by Git itself internally. By the end, you will not need any other Git resource.

Information

đŸ–Ĩī¸ Commands are shown for Bash/Zsh/PowerShell terminals. Git behaves identically across Windows, macOS, and Linux once installed.

1. Introduction to Git 📘

1.1 What is Version Control?

Version control is a system that records changes to files over time so you can recall specific versions later. Git specifically is a distributed system — every clone is a full backup of the entire project history, not just the latest snapshot.

1.2 Git vs Other VCS

FeatureGit (Distributed)SVN / CVS (Centralized)
Repository copiesFull history on every machineOnly server has full history
Offline workFully supportedLimited
Branching costCheap and instantExpensive and slow
SpeedVery fast (local operations)Slower (network dependent)

1.3 Why Git Wins

  • 📌 Tracks every change with full history
  • 🔀 Cheap, instant branching and merging
  • 🤝 Built for distributed team collaboration
  • âĒ Safe reverting and recovery mechanisms
  • 🌐 Ecosystem support: GitHub, GitLab, Bitbucket, Azure DevOps
  • ⚡ Extremely fast due to local operations
>>"Git doesn't just track files — it tracks the story of how your project came to be." — Anonymous Developer

2. Installing and Configuring Git âš™ī¸

2.1 Installation

OSCommand / Method
WindowsDownload from git-scm.com
macOSbrew install git
Ubuntu/Debiansudo apt install git
Fedora/RHELsudo dnf install git
Arch Linuxsudo pacman -S git

Check Installed Git Version

git --version

2.2 Identity Configuration

Set Global Username and Email

git config --global user.name "Your Name"
git config --global user.email "you@example.com"

Check Configured Username

git config user.name

2.3 Configuration Levels

FlagScopeFile Location
--localCurrent repository only (default).git/config
--globalAll repos for current user~/.gitconfig
--systemAll users on the machine/etc/gitconfig

2.4 Useful Configuration Settings

Set Default Editor (VS Code)

git config --global core.editor 'code --wait'

Set Default Branch Name to 'main'

git config --global init.defaultBranch main

Line Ending Handling (macOS/Linux)

git config --global core.autocrlf input

Line Ending Handling (Windows)

git config --global core.autocrlf true

Enable Colored Output

git config --global color.ui auto

Set Default Pull Strategy to Merge

git config --global pull.rebase false

View All Config With File Origins

git config --list --show-origin

Cache Credentials Temporarily

git config --global credential.helper cache

Remove a Config Value

git config --global --unset user.name

Tip

Use --global for settings that apply to all repositories, or omit it to configure only the current repository.

3. Getting Help 🆘

Open Manual Page for a Command

git help commit

Alternative Way to View Command Docs

git commit --help

Quick Inline Usage Summary

git commit -h

4. Creating and Cloning Repositories 📂

4.1 Initializing a New Repository

Initialize a New Git Repository

git init

Initialize a Repository in a New Folder

git init my-project

Create a Bare Repository (No Working Directory)

git init --bare

Initializing creates a hidden .git folder that stores all history, references, and configuration for the repository.

4.2 Cloning an Existing Repository

Clone a Remote Repository (HTTPS)

git clone https://github.com/user/repo.git

Clone a Remote Repository (SSH)

git clone git@github.com:user/repo.git

Clone into a Custom Folder Name

git clone https://github.com/user/repo.git my-folder

Shallow Clone (Only Latest Commit)

git clone --depth 1 https://github.com/user/repo.git

Clone a Specific Branch

git clone --branch develop https://github.com/user/repo.git

Clone Including All Submodules

git clone --recurse-submodules https://github.com/user/repo.git

Note

Cloning downloads the entire history of the repository by default, not just the latest snapshot. Use --depth for large repos when full history isn't needed.

5. Git Internals: How Git Actually Stores Data đŸ§Ŧ

Understanding Git's internal object model demystifies everything else. Git is fundamentally a content-addressable key-value store.

5.1 The Four Object Types

ObjectPurpose
BlobStores raw file content (no filename/metadata)
TreeRepresents a directory; maps names to blobs/trees
CommitPoints to a tree snapshot + parent commit(s) + metadata
TagA named, often signed, pointer to a commit

5.2 Plumbing Commands (Low-Level)

Compute SHA-1 Hash of a File's Content

git hash-object filename.txt

Pretty-Print Any Git Object

git cat-file -p commit-hash

Show the Type of a Git Object

git cat-file -t commit-hash

Resolve HEAD to Its Full Commit Hash

git rev-parse HEAD

List Contents of a Tree Object

git ls-tree HEAD

Information

đŸ”Ŧ Every commit hash is a SHA-1 (or SHA-256 in newer repos) digest of its content — this is why Git detects even single-byte corruption instantly.

5.3 The .git Directory Structure

PathPurpose
.git/HEADPoints to the current branch reference
.git/refs/heads/Local branch pointers
.git/refs/tags/Tag pointers
.git/objects/Compressed storage for all blobs/trees/commits
.git/configRepository-specific configuration
.git/indexThe staging area binary file

6. The Git Workflow: Three Trees 🔄

AreaDescription
Working DirectoryYour actual project files on disk
Staging Area (Index)Files marked to be included in the next commit
Repository (.git)Permanent, committed history of your project

6.1 Checking Status

View Current State of the Working Directory

git status

View Status in Short Format

git status -s

6.2 Staging Changes

Stage a Specific File

git add filename.txt

Stage an Entire Folder

git add folder/

Stage All Changes in Current Directory

git add .

Stage All Changes Including Deletions (Entire Repo)

git add -A

Stage Modified/Deleted Files Only (Not New Files)

git add -u

Interactively Stage Hunks Within a File

git add -p

Stage a New File as 'Intent to Add' (Tracks Without Content)

git add -N filename.txt

6.3 Committing Changes

Commit Staged Changes with a Message

git commit -m "Add login feature"

Stage All Tracked Files and Commit Together

git commit -am "Fix bug in auth module"

Open Editor for a Multi-line Commit Message

git commit

Modify the Last Commit's Message or Content

git commit --amend

Add Staged Changes to Last Commit Without Changing Message

git commit --amend --no-edit

Create an Empty Commit

git commit --allow-empty -m 'Trigger CI'

Create a GPG-Signed Commit

git commit -S -m 'Signed commit'

Warning

Avoid amending commits that have already been pushed to a shared remote — it rewrites history and can break collaborators' repos.

6.4 Commit Message Best Practices

  1. Use imperative mood: "Add feature" not "Added feature"
  2. Keep the subject line under 50 characters
  3. Leave a blank line, then add a detailed body if needed
  4. Reference issue numbers when relevant (e.g., Fixes #42)

7. Viewing History and Differences 🔍

7.1 Viewing Commit Logs

View Full Commit History

git log

View Condensed Commit History

git log --oneline

Visualize Full Branch History as a Graph

git log --oneline --graph --all --decorate

View Commit History with Diffs for a File

git log -p filename.txt

Filter Log by Author

git log --author='Jane'

Filter Log by Date

git log --since='2 weeks ago'

Search Commit Messages by Keyword

git log --grep='fix'

Show File Change Statistics per Commit

git log --stat

Show Commits in branch2 Not in branch1

git log branch1..branch2

Summarize Commit Counts per Author

git shortlog -sn

7.2 Viewing Differences

View Unstaged Changes

git diff

View Staged Changes (Also: --cached)

git diff --staged

Compare Two Branches

git diff branch1 branch2

Compare Current State to 3 Commits Ago

git diff HEAD~3 HEAD

Show Word-Level Differences Instead of Lines

git diff --word-diff

Compare Two Sets of Commits (e.g., Before/After Rebase)

git range-diff main~5..main main~5..origin/main

7.3 Inspecting Objects

Show Full Details of a Specific Commit

git show commit-hash

Show File Content at a Specific Commit

git show HEAD~2:filename.txt

Show Who Last Modified Each Line

git blame filename.txt

Blame Only Lines 10 to 20

git blame -L 10,20 filename.txt

8. Branching đŸŒŋ

Branches let you work on features, fixes, or experiments in isolation without affecting the main codebase. In Git, a branch is simply a lightweight, movable pointer to a commit.

8.1 Managing Branches

List All Local Branches

git branch

List All Local and Remote Branches

git branch -a

List Remote-Tracking Branches Only

git branch -r

Create a New Branch (Without Switching)

git branch feature-login

Delete a Merged Branch

git branch -d feature-login

Force Delete an Unmerged Branch

git branch -D feature-login

Rename a Branch

git branch -m old-name new-name

List Branches Already Merged into Current

git branch --merged

Find Which Branches Contain a Commit

git branch --contains commit-hash

8.2 Switching Branches

Switch to an Existing Branch (Legacy)

git checkout feature-login

Create and Switch to a New Branch (Legacy)

git checkout -b feature-payment

Switch to an Existing Branch (Modern)

git switch feature-login

Create and Switch to a New Branch (Modern)

git switch -c feature-payment

Switch Back to the Previous Branch

git switch -

Best Practice

Prefer git switch and git restore (Git 2.23+) over the overloaded git checkout in modern workflows — they're more intuitive and reduce accidental mistakes.

9. Merging and Rebasing 🔗

9.1 Merging Branches

Merge a Branch into the Current Branch

git merge feature-login

Force a Merge Commit (No Fast-Forward)

git merge --no-ff feature-login

Combine All Branch Commits into One

git merge --squash feature-login

Cancel a Merge in Progress

git merge --abort

9.2 Handling Merge Conflicts

Conflict Marker Example

<<<<<<< HEAD
Your current changes
=======
Incoming changes
>>>>>>> feature-branch
  1. Open the conflicting file(s) and manually resolve differences
  2. Remove the conflict markers (<<<<<<<, =======, >>>>>>>)
  3. Run git add filename to mark it resolved
  4. Run git commit to complete the merge

List All Files with Unresolved Conflicts

git diff --name-only --diff-filter=U

Keep Your Version of a Conflicted File

git checkout --ours filename.txt

Keep Their Version of a Conflicted File

git checkout --theirs filename.txt

Launch a Visual Merge Conflict Resolution Tool

git mergetool

9.3 Rerere (Reuse Recorded Resolution)

Enable Automatic Conflict Resolution Memory

git config --global rerere.enabled true

Tip

🧠 rerere remembers how you resolved a conflict and automatically reapplies that resolution if the same conflict appears again (common during repeated rebases).

9.4 Rebasing

Rebase Current Branch onto Main

git rebase main

Interactive Rebase (Last 3 Commits)

git rebase -i HEAD~3

Continue Rebase After Resolving a Conflict

git rebase --continue

Cancel a Rebase in Progress

git rebase --abort

Skip the Current Commit During Rebase

git rebase --skip

Replay Commits onto a Different Base

git rebase --onto main feature-old feature-new

Interactive Rebase Todo List Example

pick a1b2c3 Add login form
squash d4e5f6 Fix typo in login form
reword g7h8i9 Improve validation logic

Caution

Never rebase commits that have been pushed to a shared branch unless you're certain no one else has pulled them.

9.5 Merge vs Rebase

AspectMergeRebase
HistoryPreserves branch historyCreates linear history
Commit graphNon-linear, more complexClean and simplified
Safety on shared branchesSafeRisky (rewrites history)

10. Working with Remotes 🌐

10.1 Managing Remote Repositories

List Remote Repositories with URLs

git remote -v

Add a New Remote

git remote add origin https://github.com/user/repo.git

Rename a Remote

git remote rename origin upstream

Remove a Remote

git remote remove origin

Change a Remote's URL

git remote set-url origin git@github.com:user/repo.git

Show Detailed Info About a Remote

git remote show origin

10.2 Fetching and Pulling

Fetch Changes Without Merging

git fetch origin

Fetch from All Configured Remotes

git fetch --all

Fetch and Remove Stale Remote-Tracking Branches

git fetch --prune

Fetch and Merge Changes from Remote

git pull origin main

Pull and Rebase Instead of Merge

git pull --rebase origin main

Pull Only if a Fast-Forward is Possible

git pull --ff-only

10.3 Pushing Changes

Push Commits to Remote Branch

git push origin main

Push and Set Upstream Tracking Branch

git push -u origin feature-login

Push All Local Branches

git push --all

Push All Tags

git push --tags

Force Push (Overwrites Remote History)

git push --force

Safer Force Push (Fails if Remote Has New Commits)

git push --force-with-lease

Delete a Remote Branch

git push origin --delete feature-login

Danger

Avoid git push --force on shared branches — it can permanently delete teammates' commits. Use --force-with-lease instead, which fails safely if the remote has new commits you haven't seen.

11. Undoing Changes âĒ

11.1 Unstaging and Discarding

Discard Changes in Working Directory

git restore filename.txt

Unstage a File (Keep Changes)

git restore --staged filename.txt

Restore a File to an Older Version

git restore --source=HEAD~2 filename.txt

Discard Changes (Legacy Syntax)

git checkout -- filename.txt

11.2 Resetting Commits

Undo Last Commit, Keep Changes Staged

git reset --soft HEAD~1

Undo Last Commit, Keep Changes Unstaged (Default)

git reset --mixed HEAD~1

Undo Last Commit and Discard All Changes

git reset --hard HEAD~1

Unstage a Specific File

git reset filename.txt

Warning

git reset --hard permanently deletes uncommitted changes. Use with extreme caution.

11.3 Reverting Commits

Create a New Commit That Undoes a Previous One

git revert commit-hash

Revert a Range of Commits

git revert HEAD~3..HEAD

Revert Without Auto-Committing

git revert --no-commit commit-hash

Best Practice

Use git revert instead of git reset on public branches — it undoes changes without rewriting history, making it safe for collaboration.

12. Stashing Changes đŸ“Ļ

Stashing temporarily shelves uncommitted changes so you can switch context without committing incomplete work.

Stash Current Changes

git stash

Stash with a Descriptive Message

git stash save "WIP: navbar redesign"

Stash Including Untracked Files

git stash -u

View All Stashes

git stash list

View Full Diff of a Specific Stash

git stash show -p stash@{0}

Apply the Most Recent Stash (Keep it in List)

git stash apply

Apply a Specific Stash by Index

git stash apply stash@{2}

Apply and Remove the Most Recent Stash

git stash pop

Delete a Specific Stash

git stash drop stash@{1}

Remove All Stashes

git stash clear

Create a New Branch from a Stash

git stash branch new-branch stash@{0}

13. Tagging đŸˇī¸

Tags mark specific points in history, typically used for releases (e.g., v1.0.0).

Create a Lightweight Tag

git tag v1.0.0

Create an Annotated Tag

git tag -a v1.0.0 -m "First stable release"

Create a GPG-Signed Tag

git tag -s v1.0.0 -m 'Signed release'

List All Tags

git tag

List Tags Matching a Pattern

git tag -l 'v1.*'

Tag an Older Commit

git tag -a v0.9 commit-hash -m 'Retroactive tag'

Push a Specific Tag to Remote

git push origin v1.0.0

Push All Tags to Remote

git push origin --tags

Delete a Local Tag

git tag -d v1.0.0

Delete a Remote Tag

git push origin --delete tag v1.0.0

14. Ignoring and Tracking Files đŸšĢ

14.1 .gitignore

Example .gitignore File

# Node modules
node_modules/

# Environment variables
.env

# Build output
dist/
build/

# OS-specific files
.DS_Store

Hint

Use github.com/github/gitignore for community-maintained .gitignore templates for any language or framework.

14.2 Managing Already-Tracked Ignored Files

Stop Tracking a File Without Deleting It

git rm --cached filename.txt

Debug Why a File is Being Ignored

git check-ignore -v filename.txt

14.3 .gitattributes

Example .gitattributes File

*.jpg binary
*.sh text eol=lf
*.md diff=markdown

Information

📝 .gitattributes controls how Git handles line endings, diffing, and merging for specific file types.

15. File and Directory Operations 📁

Rename/Move a Tracked File

git mv oldname.txt newname.txt

Delete a File and Stage the Deletion

git rm filename.txt

Delete a Folder Recursively

git rm -r folder/

Untrack a File but Keep it Locally

git rm --cached filename.txt

16. Searching and Finding 🔎

Search Tracked Files for a Pattern

git grep 'TODO'

Search with Line Numbers

git grep -n 'function login'

Find Commits That Added/Removed a String (Pickaxe)

git log -S'functionName'

Find Commits Matching a Regex in Diffs

git log -G'regex.*pattern'

17. Advanced Commands 🧠

17.1 Cherry-Picking

Apply a specific commit from one branch onto another without merging the entire branch.

Apply a Specific Commit to Current Branch

git cherry-pick commit-hash

Cherry-Pick Multiple Commits

git cherry-pick commitA commitB

Cherry-Pick Without Auto-Committing

git cherry-pick --no-commit commit-hash

Abort a Cherry-Pick in Progress

git cherry-pick --abort

17.2 Bisecting (Finding Bugs)

Binary Search to Find a Bug-Introducing Commit

git bisect start
git bisect bad
git bisect good v1.0.0

End the Bisect Session and Return to Original Branch

git bisect reset

Example

Git will checkout commits one by one; mark each as good or bad until the exact faulty commit is identified.

17.3 Reflog (Recovering Lost Work)

View Reference Log of All HEAD Movements

git reflog

Recover to a Previous State Using Reflog

git reset --hard HEAD@{2}

Success

git reflog is your safety net — even after a reset --hard, lost commits can often be recovered since they aren't deleted immediately.

17.4 Submodules

Add a Submodule

git submodule add https://github.com/user/library.git libs/library

Initialize and Update Submodules

git submodule update --init --recursive

Update Submodules to Latest Remote Commit

git submodule update --remote

Remove a Submodule

git submodule deinit libs/library

17.5 Subtree

Add a Repository as a Subtree

git subtree add --prefix=libs/mylib https://github.com/user/mylib.git main --squash

Pull Updates into a Subtree

git subtree pull --prefix=libs/mylib https://github.com/user/mylib.git main --squash

17.6 Worktrees

Create a Separate Working Directory for a Branch

git worktree add ../hotfix-branch hotfix

List All Active Worktrees

git worktree list

Remove a Worktree

git worktree remove ../hotfix-branch

Information

Worktrees let you work on multiple branches simultaneously in separate folders, without stashing or switching.

17.7 Clean

Preview Untracked Files to be Removed (Dry Run)

git clean -n

Remove Untracked Files

git clean -f

Remove Untracked Files and Directories

git clean -fd

Remove Untracked and Ignored Files

git clean -fx

17.8 Archive and Patches

Export Repository as a ZIP File

git archive --format=zip HEAD -o project.zip

Create Patch Files for the Last 3 Commits

git format-patch -3

Apply a Patch File as a Commit

git am patch-file.patch

Apply a Raw Diff Without Committing

git apply changes.diff

17.9 Notes

Attach a Note to a Commit

git notes add -m 'Reviewed by QA' commit-hash

View a Commit's Notes

git notes show commit-hash

17.10 Sparse Checkout (Large Monorepos)

Checkout Only Specific Folders from a Large Repo

git sparse-checkout init --cone
git sparse-checkout set frontend/ shared/

17.11 Maintenance and Integrity

Clean Up and Optimize the Local Repository

git gc

Check Repository Integrity for Corruption

git fsck

Remove Unreachable Objects

git prune

Show Repository Object Count and Disk Usage

git count-objects -v

Enable Automatic Background Maintenance

git maintenance start

17.12 Filtering Large Files from History

Permanently Remove a File from All History (Modern Tool)

git filter-repo --path secrets.txt --invert-paths

Danger

âš ī¸ Rewriting history with filter-repo or the deprecated filter-branch changes every commit hash downstream. Coordinate with your entire team before doing this.

17.13 Git LFS (Large File Storage)

Enable Git LFS in a Repository

git lfs install

Track Large Binary Files with LFS

git lfs track '*.psd'

List Files Tracked by LFS

git lfs ls-files

18. Git Hooks đŸĒ

Hooks are scripts that run automatically at specific points in the Git workflow (e.g., before a commit or push). They live in .git/hooks/.

Example pre-commit Hook

#!/bin/sh
# .git/hooks/pre-commit
npm run lint
if [ $? -ne 0 ]; then
  echo "Lint failed. Commit aborted."
  exit 1
fi
HookTriggered When
pre-commitBefore a commit is created
commit-msgAfter the commit message is written
pre-pushBefore pushing to a remote
post-mergeAfter a successful merge

Tip

Use tools like Husky to manage Git hooks easily in JavaScript projects.

19. Authentication and Security 🔐

19.1 SSH Setup

Generate a New SSH Key

ssh-keygen -t ed25519 -C "you@example.com"

Copy Your Public Key to Add on GitHub

cat ~/.ssh/id_ed25519.pub

Test SSH Connection to GitHub

ssh -T git@github.com

19.2 GPG Commit Signing

Set Your GPG Signing Key

git config --global user.signingkey YOUR_KEY_ID

Sign All Commits Automatically

git config --global commit.gpgsign true

Best Practice

✅ Signed commits let others (and platforms like GitHub) cryptographically verify that a commit truly came from you.

20. Git Aliases ⚡

Create Useful Git Aliases

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --oneline --graph --all"
git config --global alias.undo "reset --soft HEAD~1"

Tip

After setting aliases, git st works exactly like git status — saving keystrokes daily.

21. Common Git Workflows 🧩

21.1 Feature Branch Workflow

  1. Create a branch from main: git switch -c feature-x
  2. Make changes and commit regularly
  3. Push the branch: git push -u origin feature-x
  4. Open a Pull Request for review
  5. Merge into main after approval

21.2 Gitflow Workflow

A structured branching model using dedicated branches: main, develop, feature/*, release/*, and hotfix/*. Best suited for projects with scheduled release cycles.

21.3 Trunk-Based Development

Developers commit small, frequent changes directly to main (or very short-lived branches), relying heavily on feature flags and CI/CD. Preferred by teams practicing continuous deployment.

21.4 Forking Workflow

Common in open-source projects: contributors fork the repository, make changes in their fork, then submit a Pull Request back to the original repository.

22. Troubleshooting Common Issues đŸ› ī¸

ProblemSolution
Detached HEAD stategit switch -c new-branch-name to save your work
Committed to wrong branchgit reset --soft HEAD~1 then switch and re-commit
Accidentally deleted a branchgit reflog to find the last commit hash, then git branch recovered-branch hash
Large file rejected by remoteUse git lfs or remove it with filter-repo
Merge conflict overwhelmUse git mergetool or abort with git merge --abort

Question

❓ What's a "detached HEAD"? It happens when you check out a specific commit instead of a branch — any new commits won't belong to a branch and can be lost if you switch away without saving them.

23. Complete Command Cheat Sheet 📋

CategoryKey Commands
Setupgit init, git clone, git config
Staginggit add, git rm, git mv
Committinggit commit, git commit --amend
Branchinggit branch, git switch, git checkout
Merginggit merge, git rebase, git cherry-pick
Remotegit push, git pull, git fetch, git remote
Historygit log, git diff, git show, git blame
Undogit reset, git revert, git restore
Stashinggit stash
Tagsgit tag
Debugginggit bisect, git reflog, git blame
Advancedgit submodule, git worktree, git filter-repo, git lfs
Maintenancegit gc, git fsck, git prune

24. Summary ✅

Summary

Git provides a powerful, flexible foundation for tracking changes and collaborating on code. Mastery comes from combining daily commands (add, commit, push, pull) with situational tools (rebase, cherry-pick, bisect, reflog) and understanding internals (blobs, trees, commits) when things go wrong.
  • ✅ Use clear, descriptive, imperative-mood commit messages
  • ✅ Commit small, logical changes frequently
  • ✅ Pull before you push to avoid conflicts
  • ✅ Never force-push to shared branches without --force-with-lease
  • ✅ Use .gitignore and .gitattributes to keep repositories clean
  • ✅ Enable rerere if you rebase frequently
  • ✅ Sign commits/tags with GPG for verified authorship
  • ✅ Run git gc periodically on large repositories

Reference

For the complete official reference, visit the Git Documentation. For an interactive learning experience, try Learn Git Branching.

Git is a parallel universe machine for code. Every commit = a save point. Every branch = an alternate timeline. Every merge = controlled chaos 🌌

1. Install Git

Check installation

Code Snippet

git --version

2. Initial Configuration

Set username

Code Snippet

git config --global user.name "Your Name"

Set email

Code Snippet

git config --global user.email "you@example.com"

View config

Code Snippet

git config --list

3. Create Repository

Initialize Git

Code Snippet

git init

Creates hidden .git folder 🧠

4. Git Workflow Basics

Code Snippet

Working Directory
       ↓
Staging Area
       ↓
Repository

5. Check Status

Code Snippet

git status

Shows:

  • modified files
  • staged files
  • untracked files

6. Add Files

Add single file

Code Snippet

git add app.js

Add all files

Code Snippet

git add .

7. Commit Changes

Create commit

Code Snippet

git commit -m "Added login feature"

Think of commit messages as breadcrumbs for future-you đŸĨ–

8. View Commit History

Full history

Code Snippet

git log

Short history

Code Snippet

git log --oneline

Graph history

Code Snippet

git log --oneline --graph --all

9. Branching đŸŒŗ

Create branch

Code Snippet

git branch feature-auth

View branches

Code Snippet

git branch

Switch branch

Code Snippet

git checkout feature-auth

Modern alternative:

Code Snippet

git switch feature-auth

Create + switch

Code Snippet

git checkout -b feature-auth

or

Code Snippet

git switch -c feature-auth

10. Merge Branches

Switch to main:

Code Snippet

git checkout main

Merge:

Code Snippet

git merge feature-auth

11. Delete Branch

Code Snippet

git branch -d feature-auth

Force delete:

Code Snippet

git branch -D feature-auth

12. Remote Repository 🌍

Add remote

Code Snippet

git remote add origin REPO_URL

View remotes

Code Snippet

git remote -v

13. Push Code

First push

Code Snippet

git push -u origin main

Normal push

Code Snippet

git push

14. Clone Repository

Code Snippet

git clone REPO_URL

15. Pull Latest Changes

Code Snippet

git pull

Equivalent to:

Code Snippet

git fetch
git merge

16. Fetch Changes

Code Snippet

git fetch

Downloads changes without merging.

17. Git Diff 🔍

Unstaged changes

Code Snippet

git diff

Staged changes

Code Snippet

git diff --staged

18. Undo Changes

Remove unstaged changes

Code Snippet

git restore app.js

Unstage file

Code Snippet

git restore --staged app.js

19. Reset Commits âš ī¸

Soft reset

Keeps changes.

Code Snippet

git reset --soft HEAD~1

Hard reset

Deletes changes.

Code Snippet

git reset --hard HEAD~1

20. Revert Commit

Safe undo:

Code Snippet

git revert COMMIT_ID

21. Stash Changes đŸ“Ļ

Temporarily save work.

Save stash

Code Snippet

git stash

View stash

Code Snippet

git stash list

Apply stash

Code Snippet

git stash apply

Remove stash

Code Snippet

git stash drop

22. Rename Branch

Current branch

Code Snippet

git branch -m new-name

23. Tags đŸˇī¸

Create tag

Code Snippet

git tag v1.0

Push tags

Code Snippet

git push origin --tags

24. Git Ignore đŸšĢ

Create .gitignore

Example:

Code Snippet

node_modules/
.env
dist/

25. Remove File from Git

Code Snippet

git rm file.txt

Keep local file:

Code Snippet

git rm --cached file.txt

26. Cherry Pick 🍒

Copy commit from another branch:

Code Snippet

git cherry-pick COMMIT_ID

27. Rebase đŸ§Ŧ

Cleaner history.

Code Snippet

git rebase main

Interactive:

Code Snippet

git rebase -i HEAD~3

28. View Who Changed What

Code Snippet

git blame app.js

Git detective mode đŸ•ĩī¸

29. Clean Untracked Files

Code Snippet

git clean -f

Folders too:

Code Snippet

git clean -fd

30. Git Aliases ⚡

Example:

Code Snippet

git config --global alias.s status

Now use:

Code Snippet

git s

31. SSH Authentication 🔐

Generate SSH key:

Code Snippet

ssh-keygen -t ed25519 -C "you@example.com"

Test:

Code Snippet

ssh -T git@github.com

32. Advanced Log

Code Snippet

git log --all --decorate --oneline --graph

Beautiful commit tree 🌲

33. Useful Daily Workflow

Code Snippet

git pull
git checkout -b feature
git add .
git commit -m "Feature added"
git push origin feature

34. Fix Merge Conflicts âš”ī¸

Conflict markers:

Code Snippet

<<<<<<< HEAD
Current code
=======
Incoming code
>>>>>>> branch

Steps:

Code Snippet

git add .
git commit

35. GitHub Workflow

Code Snippet

git clone URL
git checkout -b feature
git add .
git commit -m "New feature"
git push origin feature

Then create Pull Request.

36. Git Command Cheat Sheet 📜

CommandPurpose
git initInitialize repo
git cloneCopy repo
git statusCheck changes
git add .Stage files
git commitSave snapshot
git pushUpload changes
git pullDownload changes
git branchList branches
git checkoutSwitch branch
git mergeMerge branches
git stashTemporary save
git resetUndo commits
git revertSafe undo
git logView history

37. Recommended Learning Order 🧭

Code Snippet

1. init
2. status
3. add
4. commit
5. log
6. branch
7. merge
8. remote
9. push/pull
10. stash/reset/rebase

38. Golden Rules ✨

  • Commit small changes
  • Write clear commit messages
  • Pull before push
  • Never force push blindly
  • Use branches for features
  • Keep .env inside .gitignore

39. Pro Developer Commands 🧠

See remote branches

Code Snippet

git branch -a

Show one commit

Code Snippet

git show COMMIT_ID

Amend last commit

Code Snippet

git commit --amend

Force push

Code Snippet

git push --force

Danger dragon 🐉 Use carefully.

40. Real Mental Model 🌌

Code Snippet

Git ≠ file storage

Git = timeline management system

You are not editing files.

You are sculpting history. đŸĒ