Git Tip: git mv

Posted on Tue, 03/22/2016 - 19:03

Git is one of the most frustrating tools you could ever possibly use. Of course, it's also one of the most powerful. And the more you use it the more you start to uncover it's deep, dark, hidden secrets.


The Truth about Git…

Take, for example, the simple act of renaming a file. Imagine you have a Git repository that contains a file you would like to rename. Normally, you might start by renaming the file manually in your computer's native filesystem. Then, if you went back to your Git repository and ran the command git status, you would see that Git had a strange way of interpreting what you just did, when you renamed that file. That is, in the status log output, Git will think that you deleted one file and then created an entirely new file in its place.


Lies! All lies!

When that happens, you then have to tell Git to [1] remove the file that it thinks was deleted AND [2] add the file that it thinks was created. And you have to do all of this, despite the fact that, in reality, you only renamed a single file in the repository.

Only after you make both of those changes, will Git realize that you were simply renaming a single file and reflect that fact accurately if you run `git status` again.

Obviously, it seems silly to have to go through a three-step process to achieve something that should only take one step.

The solution?

git mv

With this single command, you can move or rename a file in your repository in one, simple step. This command combines all three of the previously mentioned steps: [1] renaming or moving the file in your filesystem; [2] removing the original reference in your repository; and [3] adding the new, revised reference to your repository. After that, all you need to do is commit the change to your repository as usual.

This kind of command my not seem like a big deal. But over time, as you use Git more and more, every little shortcut begins to matter more and more, in order to save time and annoyance in entering commands over and over again.

This is a test of the emergency broadcast system. this is only a test. I don't know what I should write. So I am just writing this random text to test my typing abilities. This seems to be going well. I don't think I actually need a keyboard wrist rest.

For more info on the `git mv` command, see: https://git-scm.com/docs/git-mv