Git: Deleting and Renaming Files

Git handles file deletion and renaming differently than a standard file system. Understanding these differences is crucial for avoiding confusion.

Deleting Files

There are two ways to delete files within a Git-managed project:

  1. Direct Deletion: Delete the file directly through your file system (e.g., using your operating system’s file explorer or your code editor). Git will register this as a deletion that needs to be staged and committed.

    git status  // Shows the deleted file
    git add .   // Stages the deletion
    git commit -m "Deleted file" // Commits the deletion

    To undo a direct deletion:

    git restore . // Restores the deleted file from the last commit
  2. git rm Command: Use the git rm command to delete the file and immediately stage the deletion.

    git rm <filename>
    git commit -m "Deleted file using git rm"

    To undo a git rm deletion:

    git restore --staged .  // Unstages the deletion
    git restore .           // Restores the file to the working directory

Renaming Files

Similar to deletion, there are two approaches:

  1. Direct Renaming: Rename the file directly through your file system or code editor. Git will treat this as a deletion of the old file and the addition of a new file.

    git status // Shows a deleted and added file
    git add .
    git commit -m "Renamed file"

    Undoing a direct rename is more complex; you may need to unstage and restore files individually.

  2. git mv Command: Use git mv to rename the file and automatically stage the change. This is the recommended method.

    git mv <oldfilename> <newfilename>
    git commit -m "Renamed file using git mv"

    To undo a git mv:

    git mv <newfilename> <oldfilename> // Reverse the rename

Important Notes:

  • Git tracks file changes based on the last commit. Renaming a file back to its original name will show no changes since the last commit.
  • git status is your best friend. Use it frequently to observe the status of your files after performing deletions and renames.
  • Practice these commands to become familiar with how Git handles these operations.

Using git mv is generally preferred for renaming because it’s cleaner and simplifies the process, avoiding the complexities of Git registering a delete and an add for a simple rename.