How to rename or move files in git
We use the git mv command in git to rename and move files. We only use the command for convenience. It does not rename or move the actual file, but rather deletes the existing file and creates a new file with a new name or in another folder.
Syntax
We can use the mv command in git as follows:
Rename file
git mv options oldFilename newFilename
oldFilename: The name of the file that we renamenewFilename: The new name of the file
Move file
git mv filename foldername
filename: The name of the file that is movedfoldername: The name of the folder where the file is moved
Options
The options we can use with the mv command are:
- [-f]: Force move or rename operation. Moves or renames the file even if another file of the same name exists.
- [-n]: Does not do the actual operation; only shows what would happen.
- [-k]: Skips operation that can cause an error.
- [-v]: Report the filenames as they are renamed or moved.
Code
Consider the code snippet below which demonstrates the use of the mv command:
git mv file1.txt file2.txtgit commit -m "file1.txt renamed to file2.txt"
Explanation
The code snippet above renames the file file1.txt to file2.txt using the mv command. The mv command does not rename the file. It deletes the file file1.txt and creates a new file file2.txt that has the same contents as file1.txt. This means that the code is just a shorthand for the code:
mv file1.txt file2.txtgit add file2.txtgit rm file1.txt
The commit command is used in line 3 to save the changes of renamed file to the local repository.
Free Resources