v2.x · Complete Reference

Git Commands A→Z

Every command you need · Clear explanations · Real examples

60+
Commands
10
Categories
Use Cases
⬡ Git Workflow — Data Flow Between Areas
Working Dir
Your files
git add
──→
Staging Area
Index
git commit
──→
Local Repo
.git folder
git push
──→
Remote Repo
GitHub / GitLab
⚙️
Setup & Configuration
Configure Git identity, editor, and global settings
6 commands
git config
Set Username & Email
Configure your identity that will be attached to every commit. This is the very first step after installing Git.
Example
$ git config --global user.name "Raj Patel"
$ git config --global user.email "[email protected]"
git config --list
View All Config
List all Git configuration settings currently set on your system, both global and local.
Example
$ git config --list
user.name=Raj Patel
git config editor
Set Default Editor
Choose which editor opens for commit messages. Common choices: vim, nano, code (VS Code).
Example
$ git config --global core.editor "code --wait"
# OR for vim:
$ git config --global core.editor vim
git config alias
Create Command Aliases
Create shortcuts for long Git commands to boost productivity. Very useful for frequently used commands.
Example
$ git config --global alias.st status
$ git config --global alias.co checkout
$ git st # same as git status
~/.gitignore
Global Gitignore
Set a global .gitignore file to exclude files like .DS_Store or IDE configs across all repos.
Example
$ git config --global core.excludesfile ~/.gitignore
git help
Built-in Help
Get detailed documentation for any Git command right in the terminal. Opens a man page.
Example
$ git help commit
$ git commit --help
📁
Repository Basics
Initialize, clone, and check the status of repositories
5 commands
git init
Initialize a Repository
Creates a new empty Git repo in the current directory. Creates a hidden .git folder that tracks everything.
Example
$ mkdir my-project && cd my-project
$ git init
Initialized empty Git repository in ./my-project/.git/
git clone
Clone a Repository
Download a full copy of an existing remote repository to your local machine, including all history.
Example
$ git clone https://github.com/user/repo.git
# Clone into a custom folder name:
$ git clone https://github.com/user/repo.git my-folder
git status
Check Working Status
Shows which files are staged, unstaged, or untracked. Your most-used command — run this constantly!
Example
$ git status
On branch main
Changes not staged for commit:
  modified: index.html
💡 Use -s for short output
git diff
View File Differences
Shows exact line-by-line changes between working directory and staging area, or between commits.
Example
$ git diff # unstaged changes
$ git diff --staged # staged changes
$ git diff main feature-branch
git show
Show Commit Details
Display information about a specific commit — the author, date, message, and exact code changes.
Example
$ git show # latest commit
$ git show a3b4c5d # specific hash
Staging & Committing
Add files to stage and save snapshots of your work
7 commands
git add
Stage Files
Move files from working directory to staging area to prepare them for the next commit.
Example
$ git add index.html # one file
$ git add . # all changes
$ git add -p # interactive patch mode
git commit
Save a Snapshot
Records staged changes permanently in local history with a descriptive message. Each commit is a save point.
Example
$ git commit -m "Add login page"
$ git commit -am "Fix nav bug" # add+commit
💡 Write messages in imperative mood: "Add feature" not "Added feature"
git commit --amend
Amend Last Commit
Modify the most recent commit — change its message or add forgotten files without making a new commit.
Example
$ git add forgotten.js
$ git commit --amend --no-edit
# Change message only:
$ git commit --amend -m "New message"
⚠️ Don't amend pushed commits
git rm
Remove Tracked Files
Remove a file from both the working directory and Git tracking. Stages the removal for next commit.
Example
$ git rm old-file.txt
$ git rm --cached secret.env # keep file, stop tracking
git mv
Move / Rename Files
Rename or move a file while preserving Git history, instead of manually deleting and re-adding.
Example
$ git mv old-name.js new-name.js
$ git mv utils/helper.js src/utils/helper.js
.gitignore
Ignore Files
Create a .gitignore file to tell Git which files/folders to never track — like node_modules, .env, build folders.
Example .gitignore
node_modules/
.env
dist/
*.log
.DS_Store
git restore
Discard Working Changes
Discard unstaged changes in a file, restoring it to the last committed version. Safe alternative to checkout.
Example
$ git restore index.html # discard changes
$ git restore --staged index.html # unstage
⚠️ Discards changes permanently
🌿
Branching & Merging
Create parallel lines of development and combine them
8 commands
git branch
Manage Branches
List, create, rename, or delete branches. A branch is just a pointer to a commit — lightweight and fast.
Example
$ git branch # list branches
$ git branch feature-login # create
$ git branch -d old-branch # delete
$ git branch -m new-name # rename current
git checkout
Switch Branches / Files
Switch to a different branch or restore files. Also used to create & switch in one command with -b.
Example
$ git checkout main # switch branch
$ git checkout -b feature-login # create+switch
$ git checkout a3b4c5d -- file.js # restore file
git switch
Switch Branches (Modern)
The newer, dedicated command for switching branches. Cleaner than checkout. Recommended in Git 2.23+.
Example
$ git switch main
$ git switch -c new-feature # create+switch
$ git switch - # back to previous branch
💡 Prefer switch over checkout for branches
git merge
Merge Branches
Integrate changes from one branch into another. Creates a merge commit that ties together the histories.
Example
$ git switch main
$ git merge feature-login
$ git merge --no-ff feature-login # keep merge commit
git rebase
Rebase Branch
Move or replay commits from one branch on top of another, creating a cleaner, linear history.
Example
$ git switch feature-login
$ git rebase main
$ git rebase -i HEAD~3 # interactive: squash/edit
⚠️ Never rebase shared/public branches
git cherry-pick
Pick Specific Commits
Apply a specific commit from one branch onto another without merging the entire branch.
Example
$ git cherry-pick a3b4c5d
$ git cherry-pick a3b4c5d..e5f6g7h # range
merge conflict
Resolve Merge Conflicts
When Git can't auto-merge, edit the conflict markers manually, then stage and commit the resolved files.
Resolution Steps
# 1. Open conflicting file, edit it
# 2. Remove <<<<<,=====,>>>>> markers
$ git add conflicted-file.js
$ git commit
git merge --abort
Abort a Merge
Cancel an in-progress merge and restore the state before the merge attempt started.
Example
$ git merge --abort
$ git rebase --abort # abort rebase
☁️
Remote Repositories
Connect and sync with GitHub, GitLab, Bitbucket and other remotes
7 commands
git remote
Manage Remotes
Add, remove, rename, and list remote connections. "origin" is the conventional name for the primary remote.
Example
$ git remote -v # list remotes
$ git remote add origin https://github.com/u/repo.git
$ git remote remove origin
$ git remote rename origin upstream
git push
Upload to Remote
Send committed changes from your local branch to the remote repository to share with others.
Example
$ git push origin main
$ git push -u origin feature-login # set upstream
$ git push --force-with-lease # safer force push
git pull
Download & Merge
Fetch remote changes AND merge them into your current branch in one step. Equivalent to fetch + merge.
Example
$ git pull # pull from tracked remote
$ git pull origin main
$ git pull --rebase # rebase instead of merge
git fetch
Download Without Merging
Download remote changes to your local repo without modifying your working branch. Safe way to see what's new.
Example
$ git fetch origin
$ git fetch --all # fetch all remotes
$ git fetch --prune # clean deleted remote branches
💡 Safer than pull — inspect before merging
git push --delete
Delete Remote Branch
Remove a branch from the remote repository. Useful for cleaning up merged feature branches.
Example
$ git push origin --delete feature-login
# Short form:
$ git push origin :feature-login
git remote prune
Prune Remote Branches
Remove references to remote branches that no longer exist on the remote (deleted by others).
Example
$ git remote prune origin
$ git fetch origin --prune # combined
git push --tags
Push Tags to Remote
Tags are not pushed automatically with git push. Use this to push all tags, or push a specific one.
Example
$ git push origin --tags # all tags
$ git push origin v1.0.0 # specific tag
📜
History & Logs
Explore commit history and understand what changed
6 commands
git log
View Commit History
Browse the full commit history of a branch with author, date, and message for each commit.
Example
$ git log
$ git log --oneline # compact view
$ git log --oneline --graph --all
$ git log --author="Raj"
💡 --graph shows branch visuals in terminal
git log --since
Filter Commits by Date
Narrow down history to a specific time range. Useful for sprint reviews or release notes.
Example
$ git log --since="2 weeks ago"
$ git log --after="2024-01-01"
$ git log --before="2024-06-01"
git log -S
Search Commit Content
Find commits that added or removed a specific string. Great for tracking when a function was introduced.
Example
$ git log -S"loginUser"
$ git log --grep="fix bug" # search messages
git blame
Who Changed What
Show who last modified each line of a file and in which commit. Useful for understanding why code exists.
Example
$ git blame src/app.js
$ git blame -L 10,25 app.js # lines 10-25 only
git shortlog
Summarize by Author
Summarize commit history grouped by author. Great for contribution stats in a project.
Example
$ git shortlog
$ git shortlog -sn # count only, sorted
git reflog
Reference Log (Lifesaver)
Shows a log of ALL HEAD movements including resets, rebases, and checkouts. Can recover "lost" commits!
Example
$ git reflog
a3b4c5d HEAD@{0}: commit: Add login
$ git checkout HEAD@{3} # recover lost commit
💡 The ultimate safety net in Git
↩️
Undo & Reset
Reverse changes at any stage — safely or forcefully
5 commands
git revert
Safe Undo (Creates New Commit)
Undoes a commit by creating a new commit that reverses its changes. History is preserved — safe for shared branches.
Example
$ git revert a3b4c5d # undo one commit
$ git revert HEAD # undo latest commit
$ git revert HEAD~3..HEAD # undo last 3
💡 Preferred for public/shared branches
git reset --soft
Undo Commit, Keep Staged
Move HEAD back but keep changes staged. Files stay in staging area ready to recommit. History is rewritten.
Example
$ git reset --soft HEAD~1 # undo last commit
$ git reset --soft HEAD~3 # undo last 3
git reset --mixed
Undo Commit, Keep Files
Default reset. Moves HEAD back and unstages changes, but files remain modified in working directory.
Example
$ git reset HEAD~1 # --mixed is default
$ git reset --mixed HEAD~2
git reset --hard
Completely Discard Changes
Nuclear option — moves HEAD back AND discards ALL changes in staging and working directory. Cannot be undone easily.
Example
$ git reset --hard HEAD~1
$ git reset --hard origin/main # match remote
⚠️ Destroys uncommitted work permanently
git clean
Remove Untracked Files
Delete untracked files from working directory. Use -n to preview what will be removed before doing it.
Example
$ git clean -n # dry run - preview
$ git clean -f # force delete
$ git clean -fd # delete files + dirs
⚠️ Always dry run first with -n
🗃
Stashing
Temporarily shelve changes to switch context quickly
6 commands
git stash
Stash Current Changes
Save uncommitted changes to a temporary stack and revert to a clean working directory. Perfect for context switching.
Example
$ git stash
$ git stash push -m "WIP: login form"
$ git stash --include-untracked
git stash pop
Apply & Remove Stash
Restore the most recently stashed changes back to your working directory and remove it from the stash list.
Example
$ git stash pop # latest stash
$ git stash pop stash@{2} # specific one
git stash apply
Apply Without Removing
Apply stashed changes but KEEP the stash entry in the list. Useful if you need it on multiple branches.
Example
$ git stash apply
$ git stash apply stash@{0}
git stash list
View All Stashes
Show all stash entries with their index number. Each entry is labeled stash@{n} where n is the index.
Example
$ git stash list
stash@{0}: WIP on main: Add auth
stash@{1}: WIP on main: Fix nav
git stash drop
Delete a Stash Entry
Permanently remove a specific stash entry from the stash list without applying it.
Example
$ git stash drop stash@{1}
$ git stash clear # delete ALL stashes
git stash branch
Stash to New Branch
Create a new branch from a stash entry and apply it there. Useful when stash causes conflicts on current branch.
Example
$ git stash branch new-feature stash@{0}
💡 Avoids conflicts when stash + branch diverged
🏷
Tags & Releases
Mark specific commits for releases and milestones
4 commands
git tag
Create a Tag
Mark a specific commit with a version label. Lightweight tags are just pointers; annotated tags store extra metadata.
Example
$ git tag v1.0.0 # lightweight tag
$ git tag -a v1.0.0 -m "Release v1" # annotated
$ git tag v1.0.0 a3b4c5d # tag specific commit
git tag --list
List & View Tags
Show all existing tags or view details about a specific annotated tag.
Example
$ git tag # list all tags
$ git tag -l "v1.*" # filter pattern
$ git show v1.0.0 # view tag details
git tag -d
Delete a Tag
Remove a tag locally. To remove from remote, use git push --delete after removing locally.
Example
$ git tag -d v1.0.0 # delete local
$ git push origin --delete v1.0.0 # delete remote
git describe
Describe a Commit
Give a commit a human-readable name based on the nearest tag. Useful for build versioning scripts.
Example
$ git describe
v1.0.0-3-ga3b4c5d
# v1.0.0 + 3 commits after + hash
Advanced Commands
Power tools for debugging, history rewriting, and complex workflows
8 commands
git bisect
Binary Search for Bugs
Find exactly which commit introduced a bug using binary search. Git checks out commits in the middle of the range.
Example
$ git bisect start
$ git bisect bad # current is broken
$ git bisect good v1.0.0 # this was fine
$ git bisect reset # done
git submodule
Embed Other Repos
Include another Git repository inside your repository. Common for shared libraries or dependencies.
Example
$ git submodule add https://github.com/u/lib.git
$ git submodule update --init
$ git clone --recursive repo-url
git worktree
Multiple Working Trees
Check out multiple branches simultaneously in different folders — one repo, multiple working directories.
Example
$ git worktree add ../hotfix hotfix-branch
$ git worktree list
$ git worktree remove ../hotfix
💡 Work on a hotfix without stashing current work
git archive
Export Project Snapshot
Create a zip/tar archive of a specific commit or branch without including the .git history folder.
Example
$ git archive --format=zip HEAD -o release.zip
$ git archive v1.0.0 --format=tar.gz -o v1.tar.gz
git filter-branch
Rewrite History (Advanced)
Rewrite history across all commits — e.g. remove a sensitive file that was accidentally committed everywhere.
Example
# Remove file from all history:
$ git filter-branch --tree-filter 'rm -f secret.txt' HEAD
⚠️ Use BFG Repo Cleaner for better results
git gc
Garbage Collection
Clean up unnecessary files and optimize local repository. Compresses objects and removes loose refs.
Example
$ git gc
$ git gc --aggressive # thorough cleanup
$ git gc --prune=now
git notes
Attach Notes to Commits
Add annotations or notes to commits without modifying them. Notes are stored separately from commit history.
Example
$ git notes add -m "Deployed to prod"
$ git notes show HEAD
$ git log --show-notes
git ls-files
List Tracked Files
Show all files currently tracked by Git. Helpful for debugging .gitignore or verifying what's tracked.
Example
$ git ls-files # all tracked files
$ git ls-files --others # untracked files
$ git ls-files --ignored
100%