git如何撤銷操作

這篇文章主要介紹一些基本的撤銷操作的相關命令。

一、撤銷暫存區文件

假設我們有兩個txt文件(分別爲a.txt,b.txt),不小心使用了git add .命令,兩個文件全添加到了暫存區,如何撤銷其中一個添加到暫存區的文件呢?

1.查看git狀態

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

2.撤銷暫存區中的一個文件(例如我們要撤銷的文件是b.txt),根據上面git status命令顯示的提示可知,我們應該輸入

$ git reset HEAD b.txt

3.再次查看git狀態

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

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

發現b.txt文件已經不在暫存區中了~

二、撤銷已提交的文件

假設我們想提交的文件是a.txt,此時文件處於未跟蹤狀態

假設我們有一個a.txt文件處於未跟蹤狀態,如果提交文件後,我們想撤銷此提交操作,回到上次未操作此文件時的狀態(也即是a.txt還處於未跟蹤狀態),該怎麼辦呢?

1.添加到暫存區並提交

$ git add a.txt
$ git commit -m "a.txt"

2.查看git狀態

$ git status
# Your branch is ahead of 'origin/master' by 1 commit.
#    (use "git push" to publish your local commits)

3.撤銷文件回到上次未操作時的狀態

 

$ git reset HEAD^

4.再次查看git狀態,發現文件還原到未跟蹤狀態了

$ git status
# On branch master
# Untracked files:
#    (use "git add <file>..." to include in what will be committed)
#    a.txt
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章