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