Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Renaming Files in Git | More Advanced Interaction
Git Essentials

Renaming Files in Git

Swipe to show menu

Why Rename Files?

Renaming files is a common practice in software development for various reasons:

  • Improved clarity: renaming files can enhance the clarity of your project's structure, making it easier for collaborators to understand the purpose of each file;
  • Consistency: maintaining consistent naming conventions across your project is crucial for readability and maintainability;
  • Functionality changes: as your project evolves, the functionality of certain files may change. Renaming them to reflect these changes is essential for accurate documentation.

Git Command for Renaming Files

Git simplifies the process of renaming files, and it's crucial to use Git commands to ensure that the version history remains intact. The primary command for renaming files is:

git mv old_filename new_filename

Where old_filename is the current name of the file, and new_filename is the name you want to rename to. This command performs three actions simultaneously:

  • Renames the file locally;
  • Stages the change for commit;
  • Modifies the file in the working directory.

After running this command, you can proceed to commit the changes.

Note
Note

In fact, this command can also be used to move files between directories.

Example Scenario

First, create a configuration file named cg.txt containing a single line with an example secret key value:

echo "SECRET_KEY=1234" > cg.txt
Creating config file

Now check the status of the working tree and staging area:

git status
Checking status

Add this file to the staging area:

git add cg.txt
Adding config file to the staging area

Afterward, commit this addition:

git commit -m "Add config file" 
Committing config file

The commit is successful, but the name of the config file is not very clear, so rename it to config.txt:

git mv cg.txt config.txt
Renaming config file

Once again, check the status of the working tree and staging area:

git status
Checking status

As you can see, the status shows us that the file was renamed from cg.txt to config.txt, and this change is already staged and ready to be committed.

Now commit this change:

git commit -m "Rename config file"
Committing renaming

The config file has been successfully renamed, and the commit completed successfully.

question mark

What happened after running the commands to rename the config file and commit the change?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 4

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 2. Chapter 4
some-alt