Open In App

Git – Move Files

Last Updated : 05 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Git move or mv helps us to rename or move files within a git repository without deleting its history. If we move or rename a file within a git repository then it thinks that a file is deleted and a new file is added. That results in the deletion of its commit history.

Here is the terminal shell pictorial depiction after renaming the gfg1.py file to gfg2.py  as follows:  

As you can see from this that git status shows that gfg1.py is deleted and a new file gfg2.py is added but actually we have just renamed the file using file explorer. This will also result in the deletion of any history associated with the gfg1.py file. In order to solve this, we use git mv command. git mv helps us to rename or move files without deleting their previous history. git mv comes with a couple of options as well. 

They are listed below in tabular format as follows:

Command Action Performed
-f Force renaming or moving of a file even if the target exists
-k Skip move or rename actions which would lead to an error condition
-n Do nothing; only show what would happen
-v Report the names of files as they are moved.

Now let us discuss Rename and Move operation to a greater depth:

A. Rename Operation

Now to rename a file within a git repository we will use the following command –

git mv oldfilename newfilename

Let’s take the earlier example, this time we are renaming the file using this command. The terminal shell command will be –

git mv gfg1.py gfg2.py 

Now the git knows it is a rename operation and that will be displayed when we use the git status command. Here is the terminal shell pictorial depiction for the same –

B. Move operation

Just like the rename operation using the same way we can also perform the move operation. Now to move a file within a git repository we will use the below-listed command as follows: 

git mv filename dir/filename

Example:

git mv gfg.py code/gfg.py

Let’s take a scenario where we are moving gfg.py to code/gfg.py using the above command. Here is the terminal shell pictorial depiction after executing the above commands as follows:  


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads