How to Rename Files in Git
Renaming a file in Git using your operating system's file manager (such as Windows Explorer or macOS Finder) or by using the mv
command in the terminal may lead to a surprising discovery: Git does not track this change as you would expect.
Here's an example scenario: You decide to rename a file from style.css
to styles.css
. After making the change, you type git status
.
This is what you will get in return:
$ git status
On branch main
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
deleted: style.css
Untracked files:
(use "git add <file>..." to include in what will be committed)
styles.css
no changes added to commit (use "git add" and/or "git commit -a")
As you can see from the output above, Git thinks that the original file was deleted and a new, unrelated file was created. Your commit would need to include both the original file's removal as well as the newly created file.
Not quite what you were expecting, right? 😖
Luckily, there's a better way.
The Git Cheat Sheet
No need to remember all those commands and parameters: get our popular "Git Cheat Sheet" - for free!
The Solution: the git mv
Command
To move or rename a file within your Git repository, you should use the git mv
command. This will maintain the file's history, so Git won't lose track of that file.
You'll just need to run the following command to rename the file:
$ git mv old_file_name new_file_name
Following the example mentioned earlier, this is how the command would look like:
$ git mv style.css styles.css
If you run git status
, you will see that the output is completely different, meeting your expectations. Git has successfully tracked the file rename! ✌️
$ git status
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
renamed: style.css -> styles.css
After running the git mv
command, Git will automatically stage the changes for you. You can then commit these changes to save them in your project's history.
Tip
Renaming Files in Tower
In case you are using the Tower Git client, you can simply rename a file using your file manager (or by typing the "mv" command in the Terminal), like you normally would.
Tower will detect that change and take care of everything for you in the background!
Learn More
- More frequently asked questions about Git & version control