git常用命令

本文主要内来自阮一峰的这篇文章常用 Git 命令清单,对其内容作了小部分的裁剪与增加,以更符合我个人的使用查找习惯。

最常用几个命令示意图

git配置

可供参考的git配置

当前用户的git文件目录:~/.gitconfig

1
2
3
4
5
6
7
8
9
# 显示当前的Git配置
$ git config --list

# 编辑Git配置文件
$ git config -e [--global]

# 设置提交代码时的用户信息
$ git config [--global] user.name "[name]"
$ git config [--global] user.email "[email address]"

快捷方式设置:

1
2
3
4
5
# 输入git s就代表git status
$ git config --global alias.s status

# 进入到根目录配置文件文件中修改
$ vim ~/.gitconfig

代码提交

1
2
3
4
5
6
7
8
9
10
# 推送本地仓库到远程
$ git remote add origin 远程仓库地址
$ git push -u origin master

# 提交时显示所有diff信息
$ git commit -v

# 使用一次新的commit,替代上一次提交
# 如果代码没有任何新变化,则用来改写上一次commit的提交信息
$ git commit --amend -m [message]

分支

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 新建一个分支,指向指定commit
$ git branch [branch] [commit]

# 新建一个分支,与指定的远程分支建立追踪关系
$ git branch --track [branch] [remote-branch]

# 建立追踪关系,在现有分支与指定的远程分支之间
$ git branch --set-upstream [branch] [remote-branch]

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

# 选择一个commit,合并进当前分支
$ git cherry-pick [commit]

# 衍合多个commit
$ git rebase -i HEAD~2

# 删除远程分支
$ git push origin --delete [branch-name]
$ git branch -dr [remote/branch]

标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 列出所有tag
$ git tag

# 新建一个tag在当前commit
$ git tag [tag]

# 新建一个tag在指定commit
$ git tag [tag] [commit]

# 删除本地tag
$ git tag -d [tag]

# 删除远程tag
$ git push origin :refs/tags/[tagName]

# 查看tag信息
$ git show [tag]

# 提交指定tag
$ git push [remote] [tag]

# 提交所有tag
$ git push [remote] --tags

# 新建一个分支,指向某个tag
$ git checkout -b [branch] [tag]

远程同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 下载远程仓库的所有变动
$ git fetch [remote]

# 增加一个新的远程仓库,并命名
$ git remote add [shortname] [url]

# 取回远程仓库的变化,并与本地分支合并
$ git pull [remote] [branch]

# 上传本地指定分支到远程仓库
$ git push [remote] [branch]

# 强行推送当前分支到远程仓库,即使有冲突
$ git push [remote] --force

# 非同源的两个分支合并
$ git pull origin master ----allow-unrelated-histories

撤销

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 重置当前分支的指针为指定commit,同时重置暂存区,但工作区不变
$ git reset [commit]

# 重置当前分支的HEAD为指定commit,同时重置暂存区和工作区,与指定commit一致
$ git reset --hard [commit]

# 回退当前分支HEAD n个commit
$ git reset HEAD~n

# 暂存相关操作
$ git stash
$ git stash list
$ git stash apply [stash@{2}]
$ git stash drop stash@{0}