In Git, deleting a file from your working directory (the files stored locally on your machine), and committing that change to the remote repository (the files stored in the remote server) are two separate actions. Git tracks deletions as part of its version control process, which means that even when files are deleted, their history remains in the repository for potential recovery or analysis.
This guide will show you how to manage deleted files using Git, covering everything from committing deleted files, to reverting accidental deletions.
Step 1: deleting files locally
You can delete files manually using your operating system's file management commands, or directly through Git:
git rm <file-name>
The git rm
command deletes the file from your working directory and stages the deletion for your next commit. This is the recommended method if you are sure that you want to remove the file from the repository as it streamlines the process.
Step 2: staging deleted files
If you've manually deleted a file, you need to tell Git about this deletion:
git add <deleted-file-name>
In Git, this command stages the deletion as if you used git rm
. If you're not sure which files you have deleted, you can use:
git add -u
This command stages all modifications, including deletions, for all tracked files in the current directory and subdirectories, but does not add new (untracked) files.
Step 3: committing the deletion
Once you have staged the deletions, commit them to your repository:
git commit -m "Remove specified files"
This saves the changes to your repository, effectively recording the deletions in the project history.
Special scenarios
Recovering a deleted file
If you decide that you need a file back after deleting it, but before committing the change, you can restore it using:
git restore <deleted-file-name>
This will restore the file to your working directory, essentially undoing the file deletion.
If you have already committed the deletion, you can still bring the file back using:
git checkout HEAD^ <deleted-file-name>
This command restores the deleted file to its state before the last commit, (ie. when you deleted it).
Adding all deleted files
If you have deleted multiple files and want to stage all these deletions at once, you can use:
git add -A
This command stages all changes, including new files, modifications, and deletions, across your entire project, regardless of where you are in the repository.
Reverting a commit that deleted files
If a commit was made that deleted files and you want to undo this action, use:
git revert <commit-hash>
Replace <commit-hash>
with the hash of the commit that deleted the files. This command creates a new commit that undoes the changes made by the previous commit, effectively restoring the deleted files.
For further reading on file deletions in Git, see the official Git documentation.