撤銷修改
前一篇博客介紹了版本回退,回退到已經提交的版本。
但是,這裏的修改和上一篇的回退概念不一樣,修改要分兩種情況討論:
1、只是在工作區(目錄)進行了修改,還沒有提交至暫存區(也就是要丟棄工作區的
修改)。
2、在工作進行了修改,並且已經提交至暫存區。
下面我們分別討論這兩種情況如何撤銷修改:
1、針對第一種情況很好處理:
比如我們在readme.txt
後加了一行I dont like Git
:
$ cat readme.txt
git is a version control tool
git is the most advaced version control system
i learn git now
i think git is better than SVN
i dont like git
這個時候你突然覺得不對,即使不喜歡也不能說出來啊,於是立刻想糾正它。
於是用 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")
發現我們只是在工作區更改了 readme.txt
文件,還沒有 add 或者 commit
,Git提示我們可以使用git checkout --<file>--
命令放棄在工作區進行的修改:於是乎,有了下面的一行代碼:
$ git checkout -- readme.txt //注意:--與文件名之間有空格
此時再來查看readme.txt
內容:
cat readme.txt
git is a version control tool
git is the most advaced version control system
i learn git now
i think git is better than SVN
解惑:此時可能就會有小夥伴們問:爲什麼要使用git checkout 命令,
我直接打開readme.txt 手動刪掉最後一行不就行了嘛,當然可以。
但是,我們這裏只是對一個文件增加了一行,相當於修改了某一處的某一個功能,如果你
在寫代碼的時候一次性修改(或者添加很多行),你自己都不記得自己改了哪裏,怎樣
手動恢復呢?而且你手動刪除之後還必須要 add 以及 commit 之後版本庫中的版本纔是
最新版本。
所以使用 git checkout 就解決了你很大的問題
2、已經提交至暫存區怎麼辦?
Please 記住:Git總是有辦法的 !
假如現在已經是晚上九點了,而你還在公司摸魚,996也該下班了不是,此時心裏極其不爽,於是你在readme.txt
文檔下寫下:cccccccccccccc
:還不小心添加到了暫存區:
$ cat readme.txt
gait is a version control tool
git is the most advaced version control system
i learn git now
i think git is better than SVN
cccccccccc
$ git add readme.txt
突然靈光乍現,你意識到這個問題,頓時心裏一萬個草泥馬飄過,但是你應該慶幸的是還沒有commit
,於是你使用git status
查看一下當前的狀態:
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
Git 告訴我們等待着提交(changed to be committed),但是也同時提示你使用命令 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")
這個時候提示我們沒有文件等待着提交( Changes not staged for commit:) , 只是在工作區進行了修改,於是這就回到了第一種情況,還記得上面是什麼命令嗎?對,git checkout -- <file>
(丟棄工作區的修改)
於是趕緊操作起來:
$ git checkout -- readme.txt
然後查看當前的狀態:
$ git status
On branch master
nothing to commit, working tree clean
現在,終於結束了!這就是爲自己的行爲付出的代價,所以工作和生活上還是要謹言慎行!
小結:
本節課主要講解了如何撤銷修改的操作,分爲兩種情況:
1、只是在工作區(目錄)進行了修改,還沒有提交至暫存區(丟棄工作區的修改)git checkout -- <file>
2、在工作進行了修改,並且已經提交至暫存區,分爲兩步撤銷:1)把在暫存區的內容回退到工作區git reset HEAD <file >
;2)丟棄工作區的修改:git checkout -- <file>
參考:
【1】廖雪峯Git教程
【2】Git撤銷修改和刪除文件