Course contents

Unstage a file before committing

Sign in to run this lab and save your progress

Learn

You staged a file with git add but changed your mind. You want to keep editing it before it lands in a commit. How do you take it back out of staging?

This lesson answers that, and shows you a quirk that trips up almost every Git tutorial reader: the "modern" unstage command doesn't work in a repo that has no commits yet.

Two worlds: before and after your first commit

Most Git tutorials tell you to unstage a file with:

git restore --staged README.md

Or, in older tutorials:

git reset HEAD README.md

Both of those commands mean the same thing under the hood: "restore this file's entry in the staging area to match what's in the last commit." That works fine once you have commits, because there's a "last commit" to compare against.

In a brand new repo, though, there is no last commit. HEAD (Git's name for "the current commit") doesn't point anywhere yet. Running either of the modern unstage commands here gives you:

fatal: could not resolve HEAD

Which is Git's polite way of saying "restore to what, exactly?"

The pre first commit unstage

The command that works before you have any commits is:

git rm --cached README.md

Despite the scary name (rm, remove), this is safe. The --cached flag tells Git: "just delete the entry from the staging area. Don't touch the file on disk." The file goes back to being untracked, its content untouched.

Run cat README.md after and you'll see everything still there. Run git status and you'll see it in the "Untracked files" section, exactly where it was before you ever ran git add.

Once you have a commit, use git restore --staged

After your very first commit, the modern command works and it's what you should use from that point on:

git restore --staged README.md

Same effect, cleaner semantics. But if you ever find yourself in a fresh repo and Git yells about HEAD, reach for git rm --cached.

Don't confuse this with git rm or git reset --hard

Two neighbors of these commands are much more dangerous:

  • git rm README.md (without --cached) removes the file from the staging area and deletes it from disk. Not what you want.
  • git reset --hard discards every uncommitted change in your working directory. Nuclear. Never use it as a "get out of jail" move without knowing exactly what you're throwing away.

The unstage commands above only touch the staging area. Your edits are always safe.

Your task

You staged README.md by accident — you wanted to keep editing it first. Unstage it so it's no longer in the index, but don't delete the file. After this, git status should show README.md as untracked.