This tutorial covers essential Git commands for managing files within your repository. We’ll explore deleting, renaming, and moving files, ensuring your project history remains clean and accurate.
Table of Contents
Git Delete Files
Deleting files from your Git repository requires removing the file locally and then recording this change in Git’s history. Simply deleting a file from your file explorer won’t affect Git’s tracking.
- Remove the file locally: Use your operating system’s tools (e.g.,
rm
on Linux/macOS,del
on Windows) to delete the file. - Stage the deletion: Use the
git rm
command to inform Git of the deletion.
git rm <filename>
For example: git rm my_file.txt
- Commit the deletion: Commit the changes to record the deletion in your Git history.
git commit -m "Removed my_file.txt"
Remember to use descriptive commit messages.
Deleting multiple files: Use wildcards:
git rm *.txt #Deletes all files ending in .txt
Force Deletion (Caution!): The -f
(force) flag removes uncommitted files from the staging area and your local directory. Use with caution as it’s irreversible.
git rm -f <filename>
Git Rename Files
Use the git mv
command to rename files. This command updates both your local files and Git’s tracking.
git mv <old_filename> <new_filename>
Example: git mv my_file.txt my_document.txt
After renaming, commit the changes:
git commit -m "Renamed my_file.txt to my_document.txt"
Git Move Files
Moving files is handled efficiently by git mv
, preserving the file’s history. It combines deleting from the old location and adding to the new location.
git mv <source_path> <destination_path>
Example: To move my_file.txt
from the docs
directory to the reports
directory:
git mv docs/my_file.txt reports/my_file.txt
Commit the changes:
git commit -m "Moved my_file.txt from docs to reports"
Using git mv
is crucial; manual renaming/moving and then using git add
/git rm
will lose the file’s history. Git will treat it as a new file.