コマンド
$ git rm foobar.txt
実行例
git rm [ファイル名|ディレクトリ名]
でファイルを削除します。
$ git rm foobar.txt rm 'foobar.txt'
git status
でdeletedと表示されていれば成功です。
$ git status On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) Changes to be committed: (use "git reset HEAD <file>..." to unstage) deleted: foobar.txt
インデックスから削除しても、ファイルは残したい
通常、git rm
すると指定したファイルも即座に消えてしまいます。インデックスからは削除するけど、ファイル自体は残したいという場合には--cached
オプションを指定します。
$ git rm --cached foobar.txt rm 'foobar.txt' $ ls foobar.txt hello.txt
git status
するとインデックスからは削除されますが、ファイルは残っているのでUntracked fileとして表示されます。
$ git status HEAD detached at 4f00e3b Changes to be committed: (use "git reset HEAD <file>..." to unstage) deleted: foobar.txt Untracked files: (use "git add <file>..." to include in what will be committed) foobar.txt
gitを通さずに削除するとどうなる?
実際にやってみましょう。
$ ls foobar.txt hello.txt $ rm foobar.txt
git status
で見てみると削除されたことになっています。
$ git status On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) deleted: foobar.txt
そのままcommitも出来てしまいました。git log
git show
でログを見ても正常に削除されているのがわかります。
$ git commit -am "delete" [master 43a75c4] delete 1 file changed, 1 deletion(-) delete mode 100644 foobar.txt
git rm
で明示しないと何が問題かというと、git自身はあなたがどのようなコマンドを叩いたのかすべて把握しているわけではありません。例えば以下のように名前を変更した後にgit status
すると...
$ mv foobar.txt foo.txt
foobar.txtは削除され、foo.txtが新たに登場したと認識されてしまいます。実際には違いますよね?このような事故を防ぐために一度Gitに登録したファイルを操作する際には必ずGitのコマンドを用いることが求められます。
$ git status HEAD detached at 4f00e3b Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) deleted: foobar.txt Untracked files: (use "git add <file>..." to include in what will be committed) foo.txt no changes added to commit (use "git add" and/or "git commit -a")