六、Git-撤銷修改
一、工作區的內容你修改了多次,並且儲存了多次,如果想回到修改前怎麼辦?
例一:對工作區的README.txt檔案做了4次修改,且每次都做了儲存
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
My
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
My stupid
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
My stupid boss
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
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 -- <file>
丟棄工作區修改
$ cat README.txt
1Git is a distributed version control system
2Git is free sofware distributed under the GPL
3Git tracks changes of file
$ git checkout -- README.txt
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
git checkout -- <file>
的理解?
命令git checkout -- README.txt
意思就是,把readme.txt檔案在工作區的修改全部撤銷,這裡有兩種情況:
一種是readme.txt修改後還沒有被放到暫存區,現在,撤銷修改就回到和版本庫一模一樣的狀態;
一種是readme.txt已經新增到暫存區後,又作了修改,現在,撤銷修改就回到新增到暫存區後的狀態。
總之,就是讓這個檔案回到最近一次git commit或git add時的狀態
二、如果將修改git add
到了暫存區,又後悔git add
了怎麼撤回?
例二:對README.txt增加了add,且新增到了暫存區
$ cat README.txt
Git is a distributed version control system
Git is free sofware distributed under the GPL
Git tracks changes of file
add
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: README.txt
Git告訴我們,用命令git reset HEAD <file>
撤銷暫存區的修改,放到工作區
- 執行
git reset HEAD <file>
命令
$ git reset HEAD README.txt
Unstaged changes after reset:
M README.txt
- 檢視工作區狀態
$ 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 -- <file>
命令放棄工作區修改
$ git checkout -- README.txt
$ git status
On branch master
nothing to commit, working tree clean
現在,假設你不但改錯了東西,還從暫存區提交到了版本庫,怎麼辦呢?還記得版本回退一節嗎?可以回退到上一個版本。不過,這是有條件的,就是你還沒有把自己的本地版本庫推送到遠端。還記得Git是分散式版本控制系統嗎?我們後面會講到遠端版本庫,一旦你把“stupid boss”提交推送到遠端版本庫,你就真的慘了……
小結
又到了小結時間。
場景1:當你改亂了工作區某個檔案的內容,想直接丟棄工作區的修改時,用命令git checkout -- file
。
場景2:當你不但改亂了工作區某個檔案的內容,還新增到了暫存區時,想丟棄修改,分兩步,第一步用命令git reset HEAD file
,就回到了場景1,第二步按場景1操作。
場景3:已經提交了不合適的修改到版本庫時,想要撤銷本次提交,參考版本回退一節,不過前提是沒有推送到遠端庫。
附圖