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 rename
  • newFilename: The new name of the file

Move file

git mv filename foldername
  • filename: The name of the file that is moved
  • foldername: 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.txt
git 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.txt
git add file2.txt
git rm file1.txt

The commit command is used in line 3 to save the changes of renamed file to the local repository.

Copyright ©2024 Educative, Inc. All rights reserved