git實戰11 – 使用git rm移除已追縱但未提交的檔案


建立目錄

mkdir git_test_5
cd git_test_5

建立倉庫

git init
Initialized empty Git repository in /home/ben/git_test_5/.git/

建立檔案

echo 1 > 1.txt
echo 2 > 2.txt
echo 3 > 3.txt

加入檔案到暫存區

git add 1.txt
git add 2.txt
git add 3.txt

查看狀態

git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#       new file:   1.txt
#       new file:   2.txt
#       new file:   3.txt
#

查看目錄

ll
total 12
-rw-rw-r-- 1 ben ben 2 Jul  4 10:38 1.txt
-rw-rw-r-- 1 ben ben 2 Jul  4 10:38 2.txt
-rw-rw-r-- 1 ben ben 2 Jul  4 10:38 3.txt

此時目前還未提交 commit ,在提交前移除 2.txt ,但會出錯,但 git 有提示使用 git rm –cached 2.txt 的指令

git rm 2.txt
error: '2.txt' has changes staged in the index
(use --cached to keep the file, or -f to force removal)

再一次移除已加入暫存區的檔案 2.txt

git rm --cached 2.txt
rm '2.txt'

查看狀態

git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#       new file:   1.txt
#       new file:   3.txt
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       2.txt

查看目錄

ll
total 12
-rw-rw-r-- 1 ben ben 2 Jul  4 10:38 1.txt
-rw-rw-r-- 1 ben ben 2 Jul  4 10:38 2.txt
-rw-rw-r-- 1 ben ben 2 Jul  4 10:38 3.txt

提交

git commit -m 'master 1'
[master (root-commit) a891fad] master 1
2 files changed, 2 insertions(+), 0 deletions(-)
create mode 100644 1.txt
create mode 100644 3.txt

查看狀態,檔案 2.txt 出現在未追踨的區塊中,表示成功

git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       2.txt
nothing added to commit but untracked files present (use "git add" to track)