Unstage a file in Git while keeping your edits

Unstage a file in Git while keeping your edits

Accidentally staging a change does not mean you need to discard the edit. Git can remove a file’s changes from the next commit while leaving the working copy available for further editing. The important part is choosing which location to restore.

This walkthrough uses git restore --staged, available since Git 2.23, from PowerShell. Assume that the repository already has a commit and that a tracked file named notes.txt has been edited and added to the index.


Inspect what is staged

git status --short
git diff --cached -- notes.txt

git diff --cached shows the index against HEAD: the changes currently prepared for the next commit. In the two-column short status, the left column describes the index and the right describes the working tree. A tracked edit that has been added typically appears as M before the file name.

Unstage the selected file

git restore --staged -- notes.txt

--staged targets the index. With no explicit source, the source for this staged restore is HEAD. The index entry is restored, while your edited working file remains in place. The -- separates options from the selected path.

Keep the flag: git restore notes.txt normally targets the working tree instead. Adding --worktree alongside --staged also changes the working tree, so it is unsuitable when the intention is to keep the edit.

Verify the working edit remains

git status --short
git diff --cached -- notes.txt
git diff -- notes.txt
 M notes.txt

For this example, status becomes M notes.txt. The cached diff is empty, while the ordinary diff shows the edit still present in the working tree. If you edited again after staging, the earlier status may have been MM; inspect both diffs first because the staged version and working copy can differ.

Stage the intended version again

git add -- notes.txt
git diff --cached -- notes.txt

After adjusting the content, add the file again and read the cached diff before committing. Select individual paths when other files in the repository contain unrelated work.

Account for new files and missing HEAD

If a newly added file did not exist in HEAD, unstaging normally leaves it on disk as untracked, displayed as ??. That differs from the unstaged modification of an already tracked file.

A repository with no commits has no HEAD commit to use as the default source, so the tracked-file walkthrough does not apply under the same conditions. Check the repository state before choosing an operation. Unstaging changes what is prepared for a future commit; it does not rewrite existing commit history.

References

このブラウザからの自分のアクセスを解析から除外できます。