git mv Command
git mv
Command
The git mv
command is used to move or rename files in a Git repository. It performs the move or rename operation and stages the change for the next commit. This command simplifies the process of tracking file movements and renames in Git.
What Does git mv
Do?
When you run git mv
, Git performs the following actions:
- Moves or Renames Files: It moves or renames files in the working directory.
- Stages the Change: It stages the file move or rename so that it will be included in the next commit.
Basic Syntax
git mv <source> <destination>
<source>
: The path to the file or directory you want to move or rename.<destination>
: The new path for the file or directory.
Examples
Rename a Single File
To rename a file from oldname.txt
to newname.txt
:
git mv oldname.txt newname.txt
This command renames the file and stages the change.
Move a File to a New Directory
To move a file from its current location to a new directory:
git mv file.txt new-directory/file.txt
This moves file.txt
to new-directory
and stages the move.
Rename and Move a File
To rename and move a file in one command:
git mv old-directory/oldname.txt new-directory/newname.txt
This moves oldname.txt
from old-directory
to new-directory
and renames it to newname.txt
.
Move Multiple Files
To move multiple files to a new directory:
git mv file1.txt file2.txt new-directory/
This command moves file1.txt
and file2.txt
to new-directory
.
Handling the Changes
After using git mv
, you should commit the changes to finalize the move or rename operation:
git commit -m "Rename and move files"
This creates a commit that records the file moves or renames.
Important Notes
Tracking Moves and Renames: Git automatically tracks moves and renames as a combination of file deletion and creation. By using
git mv
, you make it easier for Git to track these changes properly and ensure they are reflected correctly in the commit history.Alternative Approach: You can also manually move or rename files using standard file system commands and then stage the changes with
git add
:mv oldname.txt newname.txt git add newname.txt git rm oldname.txt
However, using
git mv
simplifies this process by combining the operations.
Summary
- Purpose:
git mv
is used to move or rename files and directories within a Git repository and stages these changes for the next commit. - Basic Syntax:
git mv <source> <destination>
- Usage: Use
git mv
to streamline the process of moving or renaming files, ensuring that these changes are properly tracked by Git.
The git mv
command is a convenient way to manage file organization and naming within your repository, making it easier to maintain a clean and well-organized project structure.