GitEssential Git Commands

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 log

Shows a list of commits, their IDs (hashes), authors, and messages.


⏪ Go Back to a Specific Commit

1. Check history:

git log

Copy the commit hash (e.g., 1a2b3c4d)

2. Reset to that commit:

git reset --hard <commit_hash>

Example:

git reset --hard 1a2b3c4d

⚠️ --hard resets 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.txt

Delete file from Git and local folder:

git rm filename.txt

🛠 Check Current Status

git status

Shows:

  • Staged files
  • Unstaged changes
  • Untracked files

🌿 View All Branches

git branch

To view remote branches too:

git branch -a

🌱 Create a New Branch

git branch new-feature

Switch to it:

git checkout new-feature

Or 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 status

To see which commit you’re on:

git log --oneline

🔄 Discard Local Changes

Discard changes to a file:

git restore filename.txt

Discard 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 diff

Staged vs last commit:

git diff --cached

🧪 Try It Yourself

Problem: Revert a Mistaken Commit

Show Code
git log
git revert <commit_hash>