该文档主要是翻译的Git官方Cheat-Sheet

安装Git

Windows用户访问Git官网,下载相应版本的程序安装,Linux用户使用yum或者apt-get等工具安装。

基础操作

基本配置

配置用户信息(用户名及邮箱)

1
2
$ git config --global user.name "[name]"
$ git config --global user.email "[email address]"

设置命令行输出为彩色

1
$ git config --global color.ui auto

建立仓库

1
2
3
4
5
# 创建一个新的的本地仓库
$ git init [project-name]

# 从指定地址下载一个完整的Git项目工程
$ git clone [url]

编辑提交

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 列出所有新的或修改过的文件
$ git status

# 为指定文件创建版本快照
$ git add [file]

# 从暂存区取回文件,保留其内容
$ git reset [file]

# 显示当前文件与暂存区文件不同
$ git diff

# 显示暂存区文件与最后一个版本的不同
$ git diff --staged

# 在版本历史中永久记录文件快照
$ git commit -m "[descriptive message]"

分支及合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 列出当前仓库中所有的本地分支
$ git branch

# 创建一个新分支
$ git branch [branch-name]

# 切换到一个指定分支
$ git checkout [branch-name]

# 合并指定分支到当前分支
$ git merge [branch]

# 删除指定分支
$ git branch -d [branch-name]

删除或重命名

1
2
3
4
5
6
7
8
# 从工作目录和暂存目录中删掉一个文件
$ git rm [file]

# 删除仓库中文件,但不删除本地
$ git rm --cached [file]

# 更改文件名
$ git mv [file-original] [file-renamed]

排除临时文件和目录

1
2
列出所有被Git忽略的文件
$ git ls-files --other --ignored --exclude-standard

搁置及恢复为完成的修改

1
2
3
4
5
6
7
8
9
10
11
# 讲更改的文件临时保存
$ git stash

# 列出所有临时保存的更改
$ git stash list

# 恢复最近保存的临时更改
$ git stash pop

# 删除最新保存的更改
$ git stash drop

浏览和查看项目文件演变

1
2
3
4
5
6
7
8
9
10
11
# 列出当前分支所有版本历史
$ git log

# 列出制定文件所有版本历史,包括重命名
$ git log --follow [file]

# 列出两个分支的不同
$ git diff [first-branch]...[second-branch]

# 显示某个提交的详细内容
$ git show [commit]

删除错误,恢复历史

1
2
3
4
5
# 撤销某个commit之后的所有提交,保存本地更改
$ git reset [commit]

# 丢弃所有的历史和变更到指定的提交
$ git reset --hard [commit]

同步更改

1
2
3
4
5
6
7
8
9
10
11
# 从指定远程仓库中下载所有的版本历史
$ git fetch [bookmark]

# 合并指定远程仓库中的特定分支到当前分支
$ git merge [bookmark]/[branch]

# 将本地分支上传到远程仓库
$ git push [alias] [branch]

# 获取远程分支到当前分支并合并
$ git pull

附录

创建ssh-key

打开shell或者Git-bash,使用ssh-keygen命令:

1
ssh-keygen -t rsa

将刚创建的ssh-key公钥~/.ssh/id_rsa.pub中的内容粘贴到Github或者GitLab相应文本框中。