You have edited a file, run git add, and noticed it belongs in a later commit. Before changing anything, save open editor buffers: Git operates on the files on disk.
This walkthrough uses a repository with an existing commit and an ordinary tracked file named notes.txt. It does not cover merge conflicts. Replace the example path with your own and run the commands from the repository root.
1. Inspect what is staged
git status --short
git diff --cached -- notes.txt
git diff -- notes.txtThe two diffs answer different questions. The cached diff shows the proposed commit relative to HEAD. The plain diff compares the working copy with the index. A file can therefore appear in both comparisons if you edited it again after staging. See the official git diff reference.
2. Unstage just the intended file
git restore --staged -- notes.txtWith --staged, restore targets the index and uses HEAD by default. The current working file is left in place. The separator before the path makes the command easier to read when substituting filenames. For a path containing spaces, quote it:
git restore --staged -- "draft notes.txt"This command requires an existing HEAD commit. If Git reports that HEAD cannot be resolved, stop: a brand-new repository before its first commit needs a different workflow. Do not remove --staged as a workaround. Restore without that option targets working files and can discard edits. These distinctions are described in the git restore documentation.
3. Confirm the result
git status --short
git diff --cached -- notes.txt
git diff -- notes.txtFor the simple tracked-file example, status changes from M in the first column to M in the second column. The first column describes the index; the second describes the working tree. After unstaging, the cached diff for this path should be empty, while the plain diff should show the saved edits. Other staged files remain candidates for your next commit. The git status reference explains the columns and special cases.
New files and partially staged edits
A newly added file that is absent from HEAD becomes untracked after unstaging; status shows two question marks. Its contents remain on disk, but ordinary git diff does not display untracked file contents. Open the file to inspect it.
For a partially staged file, unstaging preserves the latest disk contents but removes the earlier staging selection for that path. Review the file again before using git add; do not assume that the old selection is saved separately.
Before your next commit
Read the staged diff for the whole repository before committing. Confirm that only the intended paths and changes remain. Unstaging is useful for correcting commit contents; it is not a backup. Keep valuable work saved, and use your normal backup process.
No comments:
Post a Comment