Skip to content

Git - Rename Operation

As a project evolves, you might need to rename files or move them into different directories. Git provides the git mv command to handle these operations while preserving the file’s history.

Jerry decides to organize the project. He wants to move all source files into a src/ directory and also rename string_utils.c to str_ops.c for brevity. He also adds a Makefile.

[jerry@devbox project]$ pwd
/home/jerry/project
[jerry@devbox project]$ ls
README.md string_utils.c
[jerry@devbox project]$ mkdir src
[jerry@devbox project]$ echo "# Basic Makefile\nall:\n\t@echo \"Build complete (placeholder)\"" > src/Makefile
[jerry@devbox project]$ git add src/Makefile # Add the new Makefile
[jerry@devbox project]$ git mv string_utils.c src/str_ops.c # Move and rename
[jerry@devbox project]$ git status -s
A src/Makefile
R string_utils.c -> src/str_ops.c

git status -s shows A for the newly added src/Makefile and R for string_utils.c indicating it has been renamed (and moved) to src/str_ops.c. The git mv command is equivalent to manually moving/renaming the file and then using git rm --cached <old_path> and git add <new_path>.

For the commit operation, Jerry can use git commit -m "message". The -a flag could also be used (git commit -a -m "...") to automatically stage all modified tracked files and then commit, but since he already used git add for the Makefile and git mv handles staging for the rename/move, a simple git commit -m is sufficient.

[jerry@devbox project]$ git commit -m "Organize sources into src/, add Makefile, rename string_utils to str_ops"

The commit output will look something like:

[main 94f7b26] Organize sources into src/, add Makefile, rename string_utils to str_ops
2 files changed, 3 insertions(+) # Example: 3 lines in Makefile
create mode 100644 src/Makefile
rename string_utils.c => src/str_ops.c (100%) # 100% means content is identical

After committing, he pushes his changes to the remote repository:

[jerry@devbox project]$ git push origin main

The command output will indicate a successful push:

Enumerating objects: 6, done.
Counting objects: 100% (6/6), done.
...
To https://git.example.com/our_team/project.git
d1e19d3..94f7b26 main -> main

Now, other developers can pull these structural changes to update their local repositories. Git is smart enough to track the history of src/str_ops.c back to when it was string_utils.c.