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>