GIT恢复之前的版本
使用git恢复到之前的版本是个很常用的操作,比如写错的东西,或者修改了程序,程序运行的时候发现了错误,一时间也不知道问题在哪里。如果是线上的程序,就更需要马上回复了。这里做个简单的演示
演示步骤
- 创建一个空的项目
- 对同一个文件修改三次
- 恢复到第一个的版本
初始化一个空的项目
# git init
Initialized empty Git repository in /root/del/hiloong/.git/
写入第一个版本
# echo "version 1" > v.txt
# git add v.txt
# git commit -m 'version 1'
[master (root-commit) eb7be47] version 1
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 v.txt
写入第二个版本
# echo 'version 2' > v.txt
# git add v.txt
# git commit -m 'version 2'
[master 2744b17] version 2
1 files changed, 1 insertions(+), 1 deletions(-)
写入第三个版本
# echo 'version 3' > v.txt
# git add v.txt
# git commit -m 'version 3'
[master d8bdbab] version 3
1 files changed, 1 insertions(+), 1 deletions(-)
查看所有的分支记录Git reflog
查看所有分支的所有操作记录,不用git log
因为不能察看已经删除了的commit记录'
git reflog
d8bdbab HEAD@{0}: commit: version 3
2744b17 HEAD@{1}: commit: version 2
eb7be47 HEAD@{2}: commit (initial): version 1
这开始进行恢复操作 git checkout 对象的数字代码
cat v.txt
version 3
git checkout eb7be47
Note: checking out 'eb7be4'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b new_branch_name
HEAD is now at eb7be47... version 1
# 这里看到最新的结果
cat v.txt
version 1