0%

Git 学习文档 [一]

引子

Git 学习文档

Git 介绍

  • 版本控制系统
  • 分布式

Git 安装

linux 系统

Linux系统自带的软件包 没有不能装git的了吧

1
$ yum install git
1
$ apt-get install git

Macos

通过 homebrew 安装

Windows

直接下载软件包安装

配置 用户名和邮件地址

1
2
$ git config --global user.name "Your Name"
$ git config --global user.email "email.example.com"

版本库 工作区 暂存区

  • 创建文件夹
1
2
3
4
$ mkdir learngit
$ cd learngit
$ pwd
/Users/ryan/learngit
  • 初始化仓库
1
2
$ git init
Initialized empty Git repository in /Users/ryan/learngit/.git/
  • 查看当前状态
1
2
3
$ git status
# On branch master
nothing to commit (working directory clean)
  • 添加一个文件
1
$ vi readme.md

写入内容

1
Git 

  • 第二次查看当前状态
1
2
3
4
5
6
7
$ git status
# On branch master
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# readme.md
no changes added to commit (use "git add" and/or "git commit -a")
  • git add 将文件添加到仓库
1
$ git add readme.md
  • 第三次查看当前状态
1
2
3
4
5
6
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: readme.md
  • 将文件提交到仓库[git commit]
1
2
3
4
git commit -m "commit a readme file"
[master (root-commit) ba32a67] commit a readme file
1 file changed, 2 insertions(+)
create mode 100644 readme.md

参数 -m 表示提交的注释,所有提交都需要写上注释

  • 第四次查看当前状态
1
2
3
$ git status
# On branch master
nothing to commit (working directory clean)

这个地方需要解释一下

Git 有以下几个概念,要将他们搞清楚
Git 基本就能顺畅的使用了

  • 工作区/工作空间 (Working Directory)

这个很容易理解,就是你电脑里面的文件夹

  • 版本库(Repository)

两个 一个是本地版本库,一个是远程版本库

暂时先说本地版本库 本地的隐藏目录.git

工作区的修改会先提交到本地版本库中,再由本地版本库同步到远程版本库

  • 暂存区

这个是版本库里面的

第一次 在工作区中添加了文件,查看了一下状态,为 Untracked 未跟踪

第二次 git add readme.md ,其实就是将readme.md 添加到stage 暂存区里面,而且存的是修改这时查看状态就是 Changes to be committed ,准备提交

第三次 git commit -m”commit a readme file” 就是真正的将修改提交到本地分支上,当前为master
提交完以后,工作区就是“干净”的。

查看Log

Git 提供了强大的Log命令,我列举几个

  • 默认不用任何参数的话,git log 会按提交时间列出所有的更新,最近的更新排在最上面。看到了吗,每次更新都有一个 SHA-1 校验和、作者的名字和电子邮件地址、提交时间,最后缩进一个段落显示提交说明。
1
git log
  • 我们常用 -p 选项展开显示每次提交的内容差异,用 -2 则仅显示最近的两次更新:
1
git log -p -2
  • git log —stat,仅显示简要的增改行数统计:
1
git log --stat
  • git log —pretty=oneline 将每个提交放在一行显示 , 还可以用 short,full 和 fuller
1
git log --pretty=oneline
  • 最有意思的是 format,可以定制要显示的记录格式,这样的输出便于后期编程提取分析,像这样:
1
git log --pretty=format:"%h - %an, %ar : %s"

定制语法

选项 说明
%H 提交对象(commit)的完整哈希字串
%h 提交对象的简短哈希字串
%T 树对象(tree)的完整哈希字串
%t 树对象的简短哈希字串
%P 父对象(parent)的完整哈希字串
%p 父对象的简短哈希字串
%an 作者(author)的名字
%ae 作者的电子邮件地址
%ad 作者修订日期(可以用 -date= 选项定制格式)
%ar 作者修订日期,按多久以前的方式显示
%cn 提交者(committer)的名字
%ce 提交者的电子邮件地址
%cd 提交日期
%cr 提交日期,按多久以前的方式显示
%s 提交说明

还有图形化的工具可用

1
gitk

Git 学习系列


等待后续

欢迎关注我的其它发布渠道