A good[ish] website

Web development blog, loads of UI and JavaScript topics

Git: removing files from the staging area and the tree

Filed under: Source code management— Tagged with: git

Removing stuff with git: just remove any file, remove files from the staging area, how to remove files that were not supposed to be added, and how to remove everything.

Simply remove a file

Scenario 1: an unused file needs to be removed:

$ git rm <file-name>
$ git commit -m "Remove old file"

What’s the difference between rm and git rm? Not much: rm foo.txt, will remove the file, and git status will show deleted: foo.txt. But git rm foo.txt will remove the file and add it to the staging area.

Remove files from the staging area

Scenario 2: wrong files were added, but they were not yet committed, then a simple reset will remove the files from the staging area, but doesn’t actually delete the files:

$ git reset HEAD <file-name>

# Or everything
$ git reset HEAD

Remove files that should’ve been ignored

Scenario 3: make a commit and notice a stray directory or a file (for example .DS_Store) that should have been ignored in the first place, i.e.: make git forget already committed files.

First, add the file to the project’s .gitignore, and then neutralize the cache:

$ git rm --cached <file-name>

# Globbing is possible as usual
$ git rm --cached *.log

If a directory, use the -r flag:

$ git rm -r --cached directory/

Nuke all made changes for good

Scenario 4: changes in the current branch are wanted to be decimated from all eternity:

$ git reset --hard

Careful, that will remove staged and unstaged changes.

To only remove unstaged changes in the current working directory, use:

$ git checkout -- .

Also, a given amount of commits can be reset. The following will destroy the last two commits completely:

$ git reset HEAD~2 --hard

Soft reset is also possible, which is not really removing any files. This way the commits are removed, but the changed files are kept:

$ git reset HEAD~2 --soft

After that, git shows a dirty tree.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!