下麵以現實場景作為情境。 基礎知識,理解git中的幾個區域 本地代碼已經add,未commit 修改本地工作目錄中的readme.md,添加文字"第一次修改" 然後查看下狀態 進行Add操作,並查看狀態 這時候,變動進入了緩存區(Index) 但是我們突然發現我們改動錯了,其實我是想改動 文件。 方 ...
下麵以現實場景作為情境。
基礎知識,理解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操作,並查看狀態
➜ 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)
但是我們突然發現我們改動錯了,其實我是想改動experimentation.txt
文件。
方法一:我們當然可以再次修改experimentation和readme文件(刪除readme中的修改,給experimentation中添加“第一次修改”),然後再Add
方法二:我們想的可能是撤回之前的add操作,然後給experimentation中添加“第一次修改”,然後再次Add
,那這樣的話,我們如何操作呢?
撤銷某個add文件:
git reset HEAD <filename>
撤銷全部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")
回退至指定的版本,區別如下
git reset是直接刪除指定的commit之前的所有commit(這是不安全的,特別是push後),把HEAD向後移動。
git revert是一次新的commit,HEAD繼續前進,與普通的commit一樣。