BudiBadu Logo
Samplebadu

Git by Example: Unstaging Changes

2.43.0

Learn how to remove files from the staging area without losing your work. This example covers the modern git restore command and the classic git reset command.

Code

# 1. Stage a file
git add mistake.txt

# 2. Check status (it is ready to be committed)
git status

# Output:
# Changes to be committed:
#   (use "git restore --staged <file>..." to unstage)
#   modified:   mistake.txt

# 3. Unstage the file (modern way)
git restore --staged mistake.txt

# 4. Unstage the file (classic way)
git reset HEAD mistake.txt

# 5. Verify status (changes are back in working directory)
git status

# Output:
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   modified:   mistake.txt

Explanation

Unstaging changes is a common task when you accidentally add a file to the staging area that you didn't intend to commit yet. Perhaps you ran git add . out of habit but realized you included a configuration file or a debug log that shouldn't be part of the snapshot. Unstaging moves these changes back out of the "index" (staging area) but keeps them safe in your working directory.

For a long time, the command to do this was git reset HEAD <file>. While effective, the word "reset" can be intimidating and the syntax isn't very intuitive for beginners. It essentially tells Git to reset the index entry for that file to match the current HEAD commit, effectively "un-adding" it.

In recent versions of Git (2.23+), the git restore command was introduced to clarify these operations. Using git restore --staged <file> is now the recommended way to unstage work. It explicitly states that you are restoring the staged version of the file from the HEAD commit, making the action much clearer and less prone to errors.

  • Removes files from the staging area
  • Does NOT delete your modifications
  • git restore --staged is the modern command
  • git reset HEAD is the classic command

Code Breakdown

2
Adds the file to the staging area. It is now ready to be included in the next commit.
12
The modern command to unstage. The --staged flag is crucial; without it, you might accidentally overwrite your working file.
15
The classic command. It resets the index (staging area) for the specific file to match the HEAD commit.
18
Verifying the status confirms that the file is no longer staged ("Changes not staged for commit"), but your edits are still preserved in the file.