Search This Blog

September 3, 2011

Untrack a file in Git

git rm --cached <file> 

The good thing about this command is that it will merely remove the file from the history tracking index. The local copy of the file will not be removed.

The story in detail...learning by experience


[practice]$ mkdir myproject
[practice]$ cd myproject/
[myproject]$ git init
Initialized empty Git repository in /home/karthik/MyRubyProjects/practice/myproject/.git/
[myproject(master)]$ git st
# On branch master
#
# Initial commit
#
nothing to commit (create/copy files and use "git add" to track)

[myproject(master)]$ touch abc.txt
[myproject(master)]$ git st
# On branch master
#
# Initial commit
#
# Untracked files:
# (use "git add
..." to include in what will be committed)
#
# abc.txt
nothing added to commit but untracked files present (use "git add" to track)

Situation 1: If you were to untrack a newly created file that you added to staging for commit.

[myproject(master)]$ git add abc.txt

[myproject(master)]$ git st
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached
..." to unstage)
#
# new file: abc.txt

[myproject(master)]$ git rm --cached abc.txt
rm 'abc.txt'

[myproject(master)]$ git st
# On branch master
#
# Initial commit
#
# Untracked files:
# (use "git add
..." to include in what will be committed)
#
# abc.txt
nothing added to commit but untracked files present (use "git add" to track)

I now guess we are on the same page on untracking of the addition of a newly created file in Git. Let us now go ahead to add this file back and commit it to repository. This will help us gear up for the next situation - Situation 2.

[myproject(master)]$ git add .
[myproject(master)]$ git st
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use "git rm --cached 
..." to unstage)
#
# new file: abc.txt

[myproject(master)]$ git commit -m "Commit abc.txt"
[master (root-commit) a67174c] Commit abc.txt
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 abc.txt
[myproject(master)]$ git st
# On branch master
nothing to commit (working directory clean)
 


Situation 2: If you were to untrack an old file that has already been committed.

[myproject(master)]$ echo "sample text" > abc.txt
[myproject(master)]$ git st
# On branch master
# Changed but not updated:
# (use "git add
..." to update what will be committed)
# (use "git checkout --
..." to discard changes in working directory)
#
# modified: abc.txt
#
no changes added to commit (use "git add" and/or "git commit -a")

[myproject(master)]$ git rm --cached abc.txt
rm 'abc.txt'

[myproject(master)]$ git st
# On branch master
# Changes to be committed:
# (use "git reset HEAD
..." to unstage)
#
# deleted: abc.txt
#
# Untracked files:
# (use "git add
..." to include in what will be committed)
#
#
abc.txt



With that result, let us call it a day ;)