有時候項目運行後,發現修改產生了新的問題,這時候我們就要回退代碼。如果修改的代碼很少的話,可以手動修改回來,有時候修改了很多內容,甚至忘了修改了哪些內容,這時候就需要用到reset命令了,其實git提交的內容並不能真的回退,只是用以前的代碼覆蓋現在的代碼,這樣我們就不需要手動覆蓋錯誤的代碼了
[root@localhost gitdemo]# echo 'hello world'>hello.txt
[root@localhost gitdemo]# git ci -am '提交一次錯誤的代碼'
[master b00ef94] 提交一次錯誤的代碼
1 file changed, 1 insertion(+), 2 deletions(-)
[root@localhost gitdemo]# git push
我們提交了一次有問題的代碼,並push到遠端了,現在我們要回退回正確的代碼
顯示最近的n此提交
[root@localhost gitdemo]# git log -3
commit b00ef94a4841e59f60a3cd2e112bad4df6029d13
Author: chao.zeng <[email protected]>
Date: Tue Jun 14 15:39:06 2016 +0800
提交一次錯誤的代碼
commit d0ad0126b17518a61d85e8f1ec70c47a16a45532
Author: chao.zeng <[email protected]>
Date: Tue Jun 14 15:33:03 2016 +0800
tt
commit 4a8762c8c911251f513a4d0c008fd7fa75fa54b5
Author: chao.zeng <[email protected]>
Date: Tue Jun 14 09:06:40 2016 +0800
add aaa
回退到上一次提交,即 commit d0ad0126b17518a61d85e8f1ec70c47a16a45532
回退代碼用reset ,--hard會完全回退,包括頭指針,暫存區,和工作區,因爲我們要將工作區代碼回退到以前,所以使用--hard,d0ad是上次的提交號
[root@localhost gitdemo]# git reset --hard d0ad
HEAD 現在位於 d0ad012 tt
[root@localhost gitdemo]# cat hello.txt
hello
world
之前hello.txt的內容是一行'hello world',現在變成兩行了
恢復頭指針
[root@localhost gitdemo]# git reset --soft b00e
[root@localhost gitdemo]# git status
位於分支 master
您的分支與上游分支 'origin/master' 一致。
要提交的變更:
(使用 "git reset HEAD <文件>..." 以取消暫存)
修改: hello.txt
這樣我們又回到了最新的提交,即頭指針指到最新的提交,但是工作區的內容已經回退了(如果頭指針不是指向最新的提交,是無法push的)
提交
[root@localhost gitdemo]# git commit -am '回退到正確的代碼'
[master d2fd6d2] 回退到正確的代碼
1 file changed, 2 insertions(+), 1 deletion(-)
[root@localhost gitdemo]# git push
Username for 'https://git.coding.net': xiangyi
Password for 'https://[email protected]':
對象計數中: 3, 完成.
壓縮對象中: 100% (2/2), 完成.
寫入對象中: 100% (3/3), 313 bytes | 0 bytes/s, 完成.
Total 3 (delta 0), reused 0 (delta 0)
To https://git.coding.net/xiangyi/gittest.git
b00ef94..d2fd6d2 master -> master
[root@localhost gitdemo]# cat hello.txt
hello
world
[root@localhost gitdemo]#
[root@localhost gitdemo]# git log -3
commit d2fd6d2178f11a1a90622219e4e45543a6d44820
Author: chao.zeng <[email protected]>
Date: Tue Jun 14 16:13:47 2016 +0800
回退到正確的代碼
commit b00ef94a4841e59f60a3cd2e112bad4df6029d13
Author: chao.zeng <[email protected]>
Date: Tue Jun 14 15:39:06 2016 +0800
提交一次錯誤的代碼
commit d0ad0126b17518a61d85e8f1ec70c47a16a45532
Author: chao.zeng <[email protected]>
Date: Tue Jun 14 15:33:03 2016 +0800
tt
[root@localhost gitdemo]#
從log可以看出,代碼不是真的回退了,只是用之前的代碼再執行了一次提交操作並push到遠程倉庫