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!
Get our popular Git Cheat Sheet for free!
You'll find the most important commands on the front and helpful best practice tips on the back. Over 100,000 developers have downloaded it to make Git a little bit easier.
About Us
As the makers of Tower, the best Git client for Mac and Windows, we help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Ebay get the most out of Git.
Just like with Tower, our mission with this platform is to help people become better professionals.
That's why we provide our guides, videos, and cheat sheets (about version control with Git and lots of other topics) for free.