学习地址 http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000
什么是版本库呢?版本库又名仓库,英文名repository,你可以简单理解成一个目录,这个目录里面的所有文件都可以被Git管理起来,每个文件的修改、删除,Git都能跟踪,以便任何时刻都可以追踪历史,或者在将来某个时刻可以“还原”。
1. 初始化Git仓库
创建空目录
$ mkdir learngit
$ cd learngit
$ pwd
/d/mycode/learngit
把目录变成Git可以管理的仓库
$ git init
Initialized empty Git repository in d:/mycode/learngit/.git/
2. 添加文件到Git仓库
在 learngit 创建 readme.txt文件,内容是
Git is a version control system.
Git is free software.
然后
$ git add readme.txt
$ git commit -m "wrote a readme file"
[master (root-commit) 01f8c13] wrote a readme file
1 file changed, 2 insertions(+)
create mode 100644 readme.txt
3. 查看工作区状态和文件修改内容
修改的 readme.txt内容为:
Git is a distributed version control system.
Git is free software.
git status 命令可以让我们时刻掌握仓库当前的状态
$ git status
On branch 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.txt no changes added to commit (use "git add" and/or "git commit -a")
git diff 命令查看文件具体修改内容
$ git diff readme.txt
diff --git a/readme.txt b/readme.txt
index d8036c1..013b5bc 100644
--- a/readme.txt
+++ b/readme.txt
@@ -1,2 +1,2 @@
-Git is a version control system.
+Git is a distributed version control system.
Git is free software.
\ No newline at end of file
版本回退
将上面的修改上传到git仓库中,经过n次的修改和上传后,git仓库已经有好多的版本了。
git log 命令用来查看上传日志
$ git log
commit ce0986a8d1603fdeeb68e66b54ab7f696e4a602f
Author: liuchuanwei <1254428526@qq.com>
Date: Wed Dec 14 14:50:17 2016 +0800 modify readme.txt commit 01f8c13a493c3fe08c7bdfceb22a19a0b5f20189
Author: liuchuanwei <1254428526@qq.com>
Date: Wed Dec 14 14:31:19 2016 +0800 wrote a readme file
如果嫌输出的信息太多太杂乱,可以是添加参数 --pretty=oneline
$ git log --pretty=oneline
ce0986a8d1603fdeeb68e66b54ab7f696e4a602f modify readme.txt
01f8c13a493c3fe08c7bdfceb22a19a0b5f20189 wrote a readme file
git reset --hard HEAD^ 回退到上一个版本,如果回退到上上个版本,则 HEAD^^ ,当然往上100个版本写100个^比较不容易数过来,所以写成HEAD~100
。
$ git reset --hard HEAD^
HEAD is now at 01f8c13 wrote a readme file
这时再用 git log 命令来查看版本,发现版本 modify readme.txt 不见了,就好像你从21世纪坐时光穿梭机来到了19世纪,想再回去已经回不去了,肿么办?
$ git log
commit 01f8c13a493c3fe08c7bdfceb22a19a0b5f20189
Author: liuchuanwei <1254428526@qq.com>
Date: Wed Dec 14 14:31:19 2016 +0800 wrote a readme file
办法还是有的,只要找到版本 modify readme.txt 的commit_id ,即 ce0986a... ,它是用SHA1计算出的数字,用十六进制表示
git reset --hard comit_id 回到指定 commit_id 的版本,commit_id 不用写全,只要git能确定版本就行
$ git reset --hard ce0986
HEAD is now at ce0986a modify readme.txt
要重返未来,用 git reflog 查看命令历史,以便确定要回到未来的哪个版本。
$ git reflog
ce0986a HEAD@{0}: reset: moving to ce0986
01f8c13 HEAD@{1}: reset: moving to HEAD^
ce0986a HEAD@{2}: reset: moving to ce0986
01f8c13 HEAD@{3}: reset: moving to HEAD~1
ce0986a HEAD@{4}: reset: moving to ce0986
01f8c13 HEAD@{5}: reset: moving to HEAD^
ce0986a HEAD@{6}: commit: modify readme.txt
01f8c13 HEAD@{7}: commit (initial): wrote a readme file