Unstage One File in Git Without Losing Your Edits

Run git restore --staged -- path/to/file to unstage one path while keeping its working-copy edits. Check the staged diff and the working-tree diff separately, because a Git command’s destination determines what changes.

Read the two diffs before changing anything

From the repository root, run git status --short. The left status column reflects the index, which supplies the next commit. The next column reflects the working tree. Use git diff --cached -- path/to/file to inspect what is staged and git diff -- path/to/file to inspect any additional edits made after staging. The -- marks the remaining argument as a path rather than an option or revision.

This matters when one path appears in both areas. Someone may have staged an early edit and then continued writing. Unstaging normally preserves the newest working-copy version but removes the staged selection that existed in the index, so you may need to stage selected changes again later. If the staged selection itself matters, review or export it before unstaging.

Target the index and verify the result

  1. Run git restore --staged -- path/to/file using the exact relative path. Quote the path if it contains spaces.
  2. Run git diff --cached -- path/to/file again. It should be empty for the path.
  3. Run git status --short and inspect the file. A tracked file with local modifications should still appear as an unstaged change. A brand-new file usually appears as untracked.
  4. Before committing, review the full staged diff to confirm the intended files remain in the next commit.

Suppose you staged a documentation revision plus one unfinished note. After unstaging the note, the full staged diff should show the documentation revision only. The note still opens on disk. This is an illustrative example rather than a recorded repository change.

When the branch has no commits

On an unborn branch, git restore --staged may report that it cannot resolve HEAD. For an added file in that situation, inspect Git’s message and consider git rm --cached -- path/to/file, which removes the path from the index while leaving a checked-out file. Confirm the path is really the one you intend and avoid force options. If the staged and working versions differ and Git refuses, keep the file intact and review the differences before attempting anything else.

Do not substitute plain git restore -- path/to/file. Its usual destination is the working tree, where unstaged edits may be replaced.

Sources

댓글

이 블로그의 인기 게시물

소니 A6000 Wi-Fi 전송 (컴퓨터로 보내기)

SVN 서버 설치 및 웹 접속 설정-Ubuntu 14.04

VirtualBox(VM) 화면 크기 조절