Git & GitHub Course
Git & GitHub
/
Intermediate

git reset

Definition

A powerful command used to undo local changes to the state of a Git repo. It moves the `HEAD` pointer backward in time to a previous commit.

Explain Like I'm New

The ultimate Undo button. If you made 3 terrible commits, `git reset` allows you to rip those commits out of history, moving the timeline backward as if they never happened.

Real World Example

You committed a file containing your secret database password by accident. You MUST use `git reset` to completely erase that commit from local history before you push it to the internet.

Common Use Cases

  • •Erasing accidental local commits
  • •Unstaging files

Crucial Command Flags

Flag / OptionDescription
--softMove HEAD back, but keep all changes safely in the Staging Area.
--mixed(Default) Move HEAD back, unstage changes, but keep them in the Working Directory.
--hardDANGER: Move HEAD back and violently destroy all uncommitted local changes.

Terminal Output

bash / terminal
# Scenario 1: Unstaging a file $ git add . # Oops, I didn't mean to stage secret.txt! $ git reset secret.txt # Scenario 2: Erasing the last commit, but KEEPING the code in VS Code $ git reset HEAD~1 # Scenario 3: DANGER! Erasing the last commit, and DELETING the code permanently $ git reset --hard HEAD~1

Interview Questions

basic

  • Should you use `git reset` on commits that you have already pushed to GitHub?

intermediate

  • How do you unstage a file that you accidentally ran `git add` on?

Flash Cards

Question

Reset pushed commits?

Click to reveal answer
Answer

NEVER. `git reset` rewrites history. If you delete history that your coworkers have already downloaded, you will break their repositories. Only use `reset` on LOCAL commits that haven't been pushed.

Question

Unstage a file?

Click to reveal answer
Answer

`git reset <filename>` (or `git restore --staged <filename>` in newer Git versions). It pulls the file off the Stage, but leaves the edits in your Working Directory perfectly safe.