Git Mv and Rm: Rename and Remove Tracked Files
Rename a file without losing its contents
Use git mv to move a tracked file on disk and update the index in one command. Begin in the clean, disposable rename fixture described in the chapter lab; it has tracked notes.txt and obsolete.txt. The destination must not already exist.
git mv -- notes.txt shopping.txtgit status --shortgit diff --cached --name-statusExpect a staged rename (R, or R100 in the name-status diff for identical contents). The old path is absent, the new path has the same contents, and HEAD still contains the original name until you commit. Git infers renames by comparing snapshots rather than saving a permanent rename instruction.
Preview and remove a tracked file
git rm removes a tracked path from the working tree and index. In the same fixture, confirm obsolete.txt is an unwanted, committed sample file. Use the dry run first; never use force just to bypass a refusal.
git rm -n -- obsolete.txtgit rm -- obsolete.txtgit diff --cached --name-statusgit commit -m "Organize shopping notes"The dry run changes nothing. The actual command stages deletion (D). After commit the new snapshot contains shopping.txt but not obsolete.txt. Earlier commits still contain the old files. Removing a working file is not the same as erasing history.
Practice safely
In a separate fresh fixture, edit a tracked file without staging it and try a dry-run removal. Inspect the diff and status before deciding what to keep. Git normally refuses an ordinary removal that would discard changes; do not override the guard. Use -- to separate options from paths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Git Mv and Rm: Rename and Remove Tracked Files — knowledge check
Apply the file management and ignore rules taught in this lesson.
What changes immediately after git mv on a clean tracked file?
What does R100 mean in a staged comparison of identical renamed content?
Which command previews a removal?
What happens to the old committed path after a deletion commit?
Git refuses to remove a modified file. What should you do first?