Deleting Files and Directories in Git: A Guide

Learn how to remove files and directories from your Git repository using the git rm command. This guide will explain the process and provide examples to help you effectively delete unwanted content.


Git - Delete Operation

After updating his local repository, david discovers the compiled binary in the src directory. Upon checking the commit message, he realizes that tom added this compiled binary.

Step 1: Check Current Directory

Command

[david@CentOS src]$ pwd
/home/david/project/src
        

Step 2: List Files in the Directory

Command

[david@CentOS src]$ ls
Makefile string_operations string_operations.c
        

Step 3: Check the Type of the Compiled Binary

Command

[david@CentOS src]$ file string_operations
string_operations: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped
        

Step 4: View Git Commit History

Command

[david@CentOS src]$ git log
commit 29af9d45947dc044e33d69b9141d8d2dad37cc62
Author: tom Mouse 
Date: Wed Sep 11 10:16:25 2013 +0530

Added compiled binary
        

Since version control systems (VCS) are designed to store source code and not executable binaries, david decides to remove this file from the repository.

Step 5: List Files Again to Confirm

Command

[david@CentOS src]$ ls
Makefile string_operations string_operations.c
        

Step 6: Remove the Executable Binary

Command

[david@CentOS src]$ git rm string_operations
rm 'src/string_operations'
        

Step 7: Commit the Changes

Command

[david@CentOS src]$ git commit -a -m "Removed executable binary"
[master 5776472] Removed executable binary
1 files changed, 0 insertions(+), 0 deletions(-)
delete mode 100755 src/string_operations
        

Step 8: Push Changes to the Remote Repository

After committing the changes, david pushes his updates to the remote repository:

Command

[david@CentOS src]$ git push origin master
        

Step 9: Output of the Push Command

Output

Counting objects: 5, done.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 310 bytes, done.
Total 3 (delta 1), reused 0 (delta 0)
To gituser@git.server.com:project.git
29af9d4..5776472 master −> master
        

Now, the changes have been successfully reflected in the remote repository.