大話git中的撤銷操做

下面以現實場景做爲情境。html

基礎知識,理解git中的幾個區域
git

本地代碼已經add,未commit

修改本地工做目錄中的readme.md,添加文字"第一次修改"緩存

而後查看下狀態安全

➜  experimentation git:(master) ✗ git status
On branch master
Your branch is up-to-date with 'origin/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.md

no changes added to commit (use "git add" and/or "git commit -a")

進行Add操做,並查看狀態bash

➜  experimentation git:(master) ✗ git add README.md
➜  experimentation git:(master) ✗ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   README.md

➜  experimentation git:(master) ✗

這時候,變更進入了緩存區(Index)spa

可是咱們忽然發現咱們改動錯了,其實我是想改動experimentation.txt文件。code

方法一:咱們固然能夠再次修改experimentation和readme文件(刪除readme中的修改,給experimentation中添加「第一次修改」),而後再Addhtm

方法二:咱們想的多是撤回以前的add操做,而後給experimentation中添加「第一次修改」,而後再次Add,那這樣的話,咱們如何操做呢?blog

  • 撤銷某個add文件:git reset HEAD <filename>ip

  • 撤銷所有add文件:git reset HEAD .

➜  experimentation git:(master) ✗ git reset HEAD README.md
Unstaged changes after reset:
M       README.md
➜  experimentation git:(master) ✗ git status
On branch master
Your branch is up-to-date with 'origin/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.md

no changes added to commit (use "git add" and/or "git commit -a")
Tip git log與git reflog的區別
git reflog 能夠查看全部分支的全部操做記錄(包括commit,reset的操做,已經被刪除的commit記錄)
git log不能察看已經刪除的commit記錄

本地代碼已經add,已commit


將本地代碼多commit幾回,再來看下咱們的提交log

  • 方法一(推薦):執行git revert <commitId>

撤回到指定的版本,包括文件和狀態。

  • 方法二:執行git reset <commitId>
➜  experimentation git:(master) git reset 2a6c701
Unstaged changes after reset:
M       experimentation.txt
➜  experimentation git:(master) ✗ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 4 and 6 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)
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:   experimentation.txt

no changes added to commit (use "git add" and/or "git commit -a")

回退至指定的版本,區別以下

Tip git revert與git reset的區別 git reset是直接刪除指定的commit以前的全部commit(這是不安全的,特別是push後),把HEAD向後移動。 git revert是一次新的commit,HEAD繼續前進,與普通的commit同樣。
相關文章
相關標籤/搜索