A guide to moving files in Git
Git is awesome, but mistakes are inevitable. Sometimes files need to be moved/renamed. But how do you do this on a
mv old-file.txt new-file.txt
Also how should you do this with files that are already in git? Just using
mv results in one deleted file and one untracked file.
# On branch master # Changes not staged for commit: # (use "git add/rm <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # deleted: old-file.txt # # Untracked files: # (use "git add <file>..." to include in what will be committed) # # new-file.txt no changes added to commit (use "git add" and/or "git commit -a")
Why is this bad?
It results in the history of the old file to be lost and the contents of the new file to be committed as though it is new. Any subsequent
git blames will be worthless. Instead of getting a useful commit message for why something was done, you just get a “renamed file” commit. This is no use to anyone.
How can I do this in Git?
Fortunately the answer is simple. Prefix your
mv command with
git mv old-file.txt new-file.txt
git status is a lot more helpful and history is preserved.
# On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # renamed: old-file.txt -> new-file.txt #
What if I’ve already moved the file? Is all hope lost?
Git is clever. Running
git add new-file.txt and
git rm old-file.txt gives the same end result, but it does take twice as long.