MadPhysicist
MadPhysicist

Reputation: 5831

Remove Files of Certain Extension From Git Tracking After Staging

I am wondering if it is possible to remove files of specific extensions after they have been added to Git tracking.

Specifically, I have a .gitignore that already eliminates these files. However, as a result of a mishap, they may have been added to tracking. My plan now is to go and run git rm --cached on all directories and files specified in .gitignore. But I am having a difficulty addressing entries specified as file extensions.

Upvotes: 0

Views: 1119

Answers (1)

chelmertz
chelmertz

Reputation: 20601

I would use find for this, since it allows you to both specify a pattern of a filename (including .extension) and execute a command on that file.

Here's an example that does the procedure manually, for one file extension at a time:

/tmp/madphys $ git init .
Initialized empty Git repository in /tmp/madphys/.git/
/tmp/madphys HEAD$ touch lala.a
/tmp/madphys HEAD$ touch lala.b
/tmp/madphys HEAD$ mkdir dirdir
/tmp/madphys HEAD$ touch dirdir/bobo.a
/tmp/madphys HEAD$ git add .
/tmp/madphys HEAD$ git commit -m first
[master (root-commit) bfc10f1] first
 3 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 dirdir/bobo.a
 create mode 100644 lala.a
 create mode 100644 lala.b
/tmp/madphys master$ echo "*.a" > .gitignore
/tmp/madphys master$ git add -A .
/tmp/madphys master$ git commit -m ignore
[master 3e0d206] ignore
 1 file changed, 1 insertion(+)
 create mode 100644 .gitignore
/tmp/madphys master$ find . -name "*.a" -type f -exec git rm --cached {} \;
rm 'dirdir/bobo.a'
rm 'lala.a'
/tmp/madphys master$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    dirdir/bobo.a
    deleted:    lala.a

/tmp/madphys master$ git commit -m "removed"
[master 87d95d6] removed
 2 files changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 dirdir/bobo.a
 delete mode 100644 lala.a
/tmp/madphys master$ tree
.
├── dirdir
│   └── bobo.a
├── lala.a
└── lala.b

1 directory, 3 files
/tmp/madphys master$ git status
On branch master
nothing to commit, working directory clean

Upvotes: 2

Related Questions