Git 教程 - 撤銷修改

Jinku Hu 2020年6月25日 2018年7月19日
Git 教程 - 撤銷修改

在本教程中,我們將來介紹如何從暫存區撤銷修改。

從暫存區撤銷修改

在你將某些檔案修改新增到臨時區域後,有可能會遇到一種情況,就是你發現修改並不完全正確,你想繼續對檔案進行更多修改,所以你不希望將此更改提交到版本庫,這時候你需要從暫存區中撤銷該檔案的修改。

如果你用 git status 檢視的話,能夠看到檔案更改已在暫存區中,並且它還提示可以使用 git reset HEAD <file>... 命令來將修改從暫存區撤銷。

我們來看下工作區狀態,

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	renamed:    test1_rename.txt -> move/test1.txt

我們希望撤銷這次重新命名的修改,所以我們用下面的命令,

$ git reset HEAD
Unstaged changes after reset
D test1_rename.txtgi

然後,我們再來檢視工作區的狀態,它就變成了,

$ git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	deleted:    test1_rename.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	move/

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

你可以看出來,重新命名的修改已經被撤銷,工作區返回到了重新命名之前的狀態。

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn