Renaming Files in Git: A Simple Guide

Learn how to rename files in Git using the git mv command. This guide will provide step-by-step instructions and examples to help you easily change file names while maintaining your project's history.



Git - Rename Operation

So far, Tom and Jerry have been using manual commands to compile their project. Now, Jerry decides to enhance their workflow by creating a Makefile for the project and also renaming the file string.c to give it a more descriptive name.

Step 1: Check Current Directory

Command

[jerry@CentOS project]$ pwd
/home/jerry/jerry_repo/project
        

Step 2: List Files in the Directory

Command

[jerry@CentOS project]$ ls
README src
        

Step 3: Navigate to the Source Directory

Command

[jerry@CentOS project]$ cd src/
        

Step 4: Add the Makefile to the Git Staging Area

Command

[jerry@CentOS src]$ git add Makefile
        

Step 5: Rename the File

Command

[jerry@CentOS src]$ git mv string.c string_operations.c
        

Step 6: Check the Status of the Git Repository

Command

[jerry@CentOS src]$ git status -s
A Makefile
R string.c −> string_operations.c
        

The letter R before the filename indicates that the file has been renamed.

Step 7: Commit the Changes

To commit the changes, Jerry uses the -a flag with the git commit command. This flag automatically detects modified files.

Command

[jerry@CentOS src]$ git commit -a -m 'Added Makefile and renamed string.c to string_operations.c'
[master 94f7b26] Added Makefile and renamed string.c to string_operations.c
1 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 src/Makefile
rename src/{string.c => string_operations.c} (100%)
        

Step 8: Push Changes to the Remote Repository

After committing the changes, Jerry pushes his updates to the remote repository:

Command

[jerry@CentOS src]$ git push origin master
        

Step 9: Output of the Push Command

Output

Counting objects: 6, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 396 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
7d9ea97..94f7b26 master −> master
        

Now, other developers can view these modifications by updating their local repositories.