How to Untrack Files in Git
This article will introduce how to untrack files in Git.
Files within a git repository have two states: tracked
or untracked
.
Tracked files are files that Git knows about.
Untracked files are files that have been created within the working repository but have not been added using the git add
command.
Consider this scenario.
cd ~
mkdir my-repo
cd my-repo
git init
touch file.txt
git add file.txt
git commit -m 'First commit'
Git knows about file.txt
, so technically, file.txt
is now tracked.
Later on, you want to tell Git to ignore file.txt
(or any files committed by mistake) by adding this file name to .gitignore
touch .gitignore
echo 'file.txt' >> .gitignore
git add .gitignore && git commit -m 'Ignore file.txt'
What would happen?
After committing .gitignore
, you make a change to file.txt
, then git still show that file.txt
is tracked because it is still present in your repository index.
$ echo 'qwe' > file.txt
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file.txt
no changes added to commit (use "git add" and/or "git commit -a")
Untrack Files in Git
Step 1, execute the following command.
$ git rm --cache file.txt
rm 'file.txt'
$ git st
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
deleted: file.txt
rm
stop tracking and remove a file from the local repository directory.- The
--cache
option specifies that therm
command removes the file from the index only, does not remove the file from the local repository
git rm --cache file.txt
will stop tracking file.txt
by removing it from the repository index but keep the file intact.
$ git commit -m 'Remove file.txt from tracking'
[master 4697164] Remove file.txt from tracking
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 file.txt
From now on, Git won’t track any changes made to file.txt
.
$ echo '123' > file.txt
$ git st
On branch master
nothing to commit, working tree clean