Git 配置


用户信息

1
2
$ git config --global user.name "Zliu"
$ git config --global user.email zliu@example.com

文本编辑器

1
$ git config --global core.editor emacs

查看配置

1
$ git config --list

求助

1
$ git help <verb>

忽略文件

新建 .gitignore 文件,列出忽略文件。

  • 星号(*)匹配零个或多个任意字符;
  • [abc] 匹配任何一个列在方括号中的字符(这个例子要么匹配一个 a,要么匹配一个 b,要么匹配一个 c);
  • 问号(?)只匹配一个任意字符;如果在方括号中使用短划线分隔两个字符,表示所有在这两个字符范围内的都可以匹配(比如 [0-9] 表示匹配所有 0 到 9 的数字)。
1
2
3
4
5
6
7
8
9
10
11
12
13
# 此为注释 – 将被 Git 忽略
# 忽略所有 .a 结尾的文件
*.a
# 但 lib.a 除外
!lib.a
# 仅仅忽略项目根目录下的 TODO 文件,不包括 subdir/TODO
/TODO
# 忽略 build/ 目录下的所有文件
build/
# 会忽略 doc/notes.txt 但不包括 doc/server/arch.txt
doc/*.txt
# ignore all .txt files in the doc/ directory
doc/**/*.txt

Git 仓库


本地初始化

1
$ git init

从现有仓库克隆

1
$ git clone git://github.com/schacon/grit.git [<Folder Name>]

查看远程仓库

  • origin 是 Git 给你克隆的仓库服务器的默认名字
1
2
3
4
$ git remote

# 查看某个远程仓库的详细信息
$ git remote show [remote-name]

添加远程仓库

1
$ git remote add [shortname] [url]

从远程仓库抓取数据

1
$ git fetch [remote-name]

从远程仓库拉取分支

1
$ git pull [remote-name] [remote-branch]:[local-branch]

推送数据到远程仓库

1
$ git push [remote-name] [branch-name]

远程仓库的删除和重命名

1
2
3
4
5
# 修改某个远程仓库在本地的简称
$ git remote rename [old-name] [new-name]

# 移除远程仓库
$ git remote rm [shortname]

Git 更新


查看状态

1
$ git status

跟踪新文件/暂存已修改文件

1
$ git add <file>

取消跟踪文件

1
2
3
4
5
# 同时删除文件
$ git rm <file>

# 保留文件
$ git rm --cached <file>

取消暂存文件

1
git reset HEAD <file>

提交更新

1
$ git commit

还原已修改文件

1
2
3
4
5
6
7
8
9
# 恢复指定文件(最后一次commit)到工作区
$ git checkout <file>

# 恢复所有文件(最后一次commit)到工作区
$ git checkout .

# 恢复某个commit的指定文件到工作区
$ git checkout <commit-id> <file>

Git 历史


查看历史

1
2
3
4
5
6
7
8
9
# 显示所有更新(SHA1,Author,Date,Message)
$ git log

# 显示所有更新(SHA1,Author,Date,Message + 更新文件摘要)
$ git log --stat

# 显示某次更新
$ git show [commitId] [fileName]

Git 分支


新建与切换分支

1
2
3
4
5
6
7
8
# 新建分支
$ git branch <branchName>

# 切换到分支
$ git checkout <branchName>

# 新建并切换到分支
$ git checkout -b <branchName> <remote-branch>

合并分支

1
$ git merge <branchName>

删除分支

1
$ git branch -d <branchName>

重命名分支

1
$ git branch -m <old-branchName> <new-branchName>

关联远程分支

1
$ git branch --set-upstream-to origin/branchname

查看分支

1
2
3
4
5
# 查看本地分支
$ git branch

# 查看远程分支
$ git branch -r

Git 打标签


查看标签

1
2
# 查看所有标签
$ git tag

新建标签

1
2
3
4
5
# 含附注的标签
$ git tag -a [tag-name] -m [message]

# 轻量级标签
$ git tag [tag-name]

分享标签

默认情况下,git push 并不会把标签传送到远端服务器上,只有通过显式命令才能分享标签到远端仓库。

1
2
3
4
5
# 推送单个标签
$ git push origin [tag-name]

# 推送所有标签
$ git push origin --tags