Moving Files and Directories in Git: A Simple Guide

Learn how to easily move files and directories within your Git project using the git mv command. This guide will provide step-by-step instructions and examples to help you relocate files and directories efficiently.



Git - Move Operation

The move operation in Git allows you to relocate a directory or a file from one location to another within your project. For example, david decides to move the source code file into a newly created src directory. The modified directory structure will appear as follows:

Initial Directory Structure

[david@CentOS project]$ pwd
/home/david/project

[david@CentOS project]$ ls
README string string.c
        

First, david creates the src directory:

Creating the src Directory

[david@CentOS project]$ mkdir src
        

Next, he uses the git mv command to move the file:

Moving the File

[david@CentOS project]$ git mv string.c src/
        

After the move operation, david checks the status of his Git repository:

Checking Git Status

[david@CentOS project]$ git status -s
R string.c −> src/string.c
?? string
        

To make the changes permanent, david commits the modified directory structure:

Committing the Changes

[david@CentOS project]$ git commit -m "Modified directory structure"
[master 7d9ea97] Modified directory structure
1 files changed, 0 insertions(+), 0 deletions(-)
rename string.c => src/string.c (100%)
        

Finally, he pushes the changes to the remote repository so that other developers can see the updated structure:

Pushing Changes to Remote

[david@CentOS project]$ git push origin master
Counting objects: 4, done.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 320 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To gituser@git.server.com:project.git
e86f062..7d9ea97 master −> master
        

In tom’s local repository, before pulling the latest changes, the directory structure shows the old format:

tom's Initial Directory Structure

[tom@CentOS project]$ pwd
/home/tom/tom_repo/project

[tom@CentOS project]$ ls
README string string.c
        

After tom performs a pull operation, the directory structure updates, allowing him to see the src directory and the file within it:

Pulling Changes

[tom@CentOS project]$ git pull
remote: Counting objects: 4, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From git.server.com:project
e86f062..7d9ea97 master −> origin/master
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 7d9ea97683da90bcdb87c28ec9b4f64160673c8a.
        

Now, tom can check the updated directory structure:

Updated Directory Structure

[tom@CentOS project]$ ls
README src string
        

And finally, he can see the contents of the src directory:

Contents of src Directory

[tom@CentOS project]$ ls src/
string.c