Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Delete files from a Git Branch

Tags:

git

I am learning Git. In my test repo on my machine are 2 branches:

  • master and
  • testing

I did check out testing branch and deleted some files on the file system:

helpers.php                 registry.class.php
...       session.class.php                    simpleCrud.php

I then run git add .

  • I would expect these deleted files to be removed from the testing branch and allow me to commit that change
  • however git status (see image below) shows they are not available for git commit -m "Deleted some files from testing branch"

git status

  1. Can someone tell me what I am doing wrong?
  2. And how to do what I am trying to do?
like image 481
JasonDavis Avatar asked Jan 28 '26 07:01

JasonDavis


1 Answers

The reason your file deletion changes do not show up in git's index is because you removed the files yourself without informing git.

There are two ways now to fix this.

Option 1:

Use the git add -u <FILES> command to make the files tracked in the index reflect the changes in your work-tree. Git would detect the file deletions in your work-tree, and update the index to correspond to this state.

# Example command to update the git index to
# reflect the state of the files in the work-tree
# for the two files named helpers.php and registry.class.php
git add -u helpers.php registry.class.php

Option 2:

To delete a file, instead of deleting it manually using del or rm commands in your shell, you could directly ask git to remove and note down the change in the index using the git rm command. Note that this command can also be executed, even if you have already deleted the files yourself (like the case you mention).

# Example command to remove two files named
# helpers.php and registry.class.php
git rm helpers.php registry.class.php

With either of the options above you should see that your status command should automatically indicate that the files have been deleted in the staging area:

git status
# On branch testing
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   deleted:    helper.php
#   deleted:    registry.class.php
#

Then you should be able to commit the changes using the commit command.

git commit -m "Deleted some files from testing branch"
like image 126
Tuxdude Avatar answered Jan 30 '26 21:01

Tuxdude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!