Essential Git Commands
Git provides powerful commands to inspect, reset, and manage your project. Hereβs a handy reference for common tasks.
π View Commit History
git logShows a list of commits, their IDs (hashes), authors, and messages.
βͺ Go Back to a Specific Commit
1. Check history:
git logCopy the commit hash (e.g., 1a2b3c4d)
2. Reset to that commit:
git reset --hard <commit_hash>Example:
git reset --hard 1a2b3c4dβ οΈ
--hardresets your working directory and discards uncommitted changes.
π§Ή Soft Reset (keep changes)
git reset --soft <commit_hash>Moves HEAD to an earlier commit but keeps your code and staging.
β Remove a File from Repo
Keep the file locally, remove from Git:
git rm --cached filename.txtDelete file from Git and local folder:
git rm filename.txtπ Check Current Status
git statusShows:
- Staged files
- Unstaged changes
- Untracked files
πΏ View All Branches
git branchTo view remote branches too:
git branch -aπ± Create a New Branch
git branch new-featureSwitch to it:
git checkout new-featureOr combine both:
git checkout -b new-featureπ Merge Branches
Switch to the branch you want to merge into (usually main), then:
git merge new-featureπ§ See Where You Are (HEAD, Branch)
git statusTo see which commit youβre on:
git log --onelineπ Discard Local Changes
Discard changes to a file:
git restore filename.txtDiscard all unstaged changes:
git restore .π§½ Unstage a File
git restore --staged filename.txtπ Revert a Commit (undo but keep history)
git revert <commit_hash>This creates a new commit that undoes the changes from the given commit β safer than reset.
π See Differences
Unstaged vs last commit:
git diffStaged vs last commit:
git diff --cachedπ§ͺ Try It Yourself
Problem: Revert a Mistaken Commit
Show Code
git log
git revert <commit_hash>Last updated on