1.未 git add 的修改
先在在 readme.txt 中添加如下內容:
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
Git tracks changes of files.
My stupid boss still prefers SVN.
用 git status 查看一下:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: readme.txt
no changes added to commit (use "git add" and/or "git commit -a")
可以發現,Git 會告訴你,git checkout -- file 可以丟棄工作區的修改:
$ git checkout -- readme.txt
命令 git checkout -- readme.txt 意思就是,把 readme.txt 文件在工作區的修改全部撤銷,這里有兩種情況:
一種是 readme.txt 自修改后還沒有被放到暫存區,現在,撤銷修改就回到和版本庫一模一樣的狀態;
一種是 readme.txt 已經添加到暫存區后,又作了修改,現在,撤銷修改就回到添加到暫存區后的狀態。
總之,就是讓這個文件回到最近一次 git commit 或 git add 時的狀態。
2.已 git add 的修改
假如修改了 readme.txt,并且執行了 git add 命令:
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
Git tracks changes of files.
My stupid boss still prefers SVN.
$ git add readme.txt
現在該怎么撤回修改呢?我們先用 git status 查看一下,修改只是添加到了暫存區,還沒有提交:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: readme.txt
Git 同樣告訴我們,用命令 git reset HEAD file 可以把暫存區的修改撤銷掉(unstage),重新放回工作區:
$ git reset HEAD readme.txt
Unstaged changes after reset:
M readme.txt
git reset 命令既可以回退版本,也可以把暫存區的修改回退到工作區。當我們用 HEAD 時,表示最新的版本。
再用 git status 查看一下,現在暫存區是干凈的,工作區有修改:
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: readme.txt
no changes added to commit (use "git add" and/or "git commit -a")
最后我們撤回工作區的修改:
$ git checkout -- readme.txt