常用Git指令

新建代码库

1
2
3
4
5
6
7
8
# 初始化Git代码库
$ git init

# 新建一个代码库,初始化为Git代码库
$ git init <project-name>

# 克隆一个仓库项目
$ git clone <url>

增加/删除文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 添加指定文件到暂存区
$ git add <file1> <file2> ...

# 添加指定目录到暂存区
$ git add <dir>

# 添加全部文件到暂存区
$ git add .

# 删除暂存区文件
$ git rm --cached <file>

# 强制删除暂存区和工作区文件
$ git rm -f <file>

代码提交

1
2
3
4
5
6
7
8
# 提交暂存区到仓库区
$ git commit -m <message>

# 提交暂存区的指定文件到仓库区
$ git commit <file1> <file2> ... -m <message>

# 改写上一次提交
$ git commit -amend -m <message>

分支

查看分支

1
2
3
4
5
6
7
8
# 查看所有本地分支
$ git branch

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

# 查看所有本地和远程分支
$ git branch -a

创建新分支

1
2
3
4
5
6
7
8
# 基于当前分支,创建但不切换
$ git branch <new-branch>

# 基于当前分支,创建并切换
$ git checkout -b <new-branch>

# 基于远程分支,创建追踪分支
$ git branch --track <branch> <remote-branch>

切换分支

1
2
3
4
5
6
# 切换到指定分支
$ git checkout <branch>
$ git swithch <branch>

# 切换到上一个分支
$ git checkout -

合并分支

1
2
3
4
5
6
7
8
# 快速合并指定分支到当前分支
$ git merge <branch>

# 不快速合并指定分支到当前分支
$ git merge --no-ff <branch>

# 合并压缩
$ git merge --squash <branch>

删除分支

1
2
3
4
5
# 删除本地分支
$ git branch -d <branch>

# 删除远程分支
$ git push origin :<branch>

查看信息

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 查看仓库当前的状态
$ git status

# 查看当前分支的历史提交记录
$ git log

# 查看提交以图形化方式
$ git log --graph --pretty=oneline --abbrev-commit

# 查看暂存区和工作区的差异
$ git diff

# 查看最近几次提交
$ git reflog

# 查看某次提交的信息
$ git show <commit>

远程同步

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 下载远程仓库的所有改动
$ git fetch <remote>

# 显示所有远程仓库
$ git remote -v

# 显示某个远程仓库的信息
$ git remote show <remote>

# 添加新的远程仓库,自定义命名
$ git remote add <shortname> <url>

# 同步远程仓库的变化合并到本地分支
$ git pull <remote> <branch>

# 推送本地指定分支到远程仓库
$ git push <remote> <branch>

# 推送本地分支到远程仓库并创建远程分支
$ git push --set-upstream origin <branch>

# 推送本地指定分支到远程仓库其他分支
$ git push origin <branch>:<new-branch>