Git使用的常用命令

一、git工作流程

  • Workspace工作区:是当前工作目录,可以在此目录编辑文件
  • Index缓存区:add指令,保存文件的改动
  • Repository仓库:commit指令,将多次的文件改动最后提交
  • Remote远程仓库:可以将本地仓库代码传到远程仓库上,方便多人远程协作

二、常用操作

1、初始化仓库

$ git init

2、加到缓存区

# 指定文件,提交到暂存区
$ git add <filename>

# 将工作区的变化提交到暂存区,包括文件修改和新增,但是不包括删除的文件
$ git add .

# 将工作区的变化提交到暂存区,包括新增,删除和修改的所有内容
$ git add -A

3、提交到版本库

# 将修改从暂存区提交到版本库,并添加备注message
$ git commit -m “message”

4、查看信息

# 查看上次提交之后是否有修改
$ git status
# 查看上次提交之后是否有修改,简短输出结果
$ git status -s

# 查看尚未缓存的改动
$ git diff
# 查看已缓存的改动
$ git diff -cached
# 查看已缓存的与未缓存的所有改动
$ git diff HEAD

# 显示当前分支的版本历史
$ git log
# 显示commit历史,以及每次commit发生变更的文件
$ git log --stat
# 显示指定文件相关的每一次diff
$ git log -p [file]

5、回退操作

# 恢复暂存区的指定文件到工作区
$ git checkout [file]
 
# 恢复某个commit的指定文件到暂存区和工作区
$ git checkout [commit] [file]
 
# 恢复暂存区的所有文件到工作区
$ git checkout .
 
# 重置暂存区的指定文件,与上一次commit保持一致,但工作区不变
$ git reset [file]
 
# 重置暂存区与工作区,与上一次commit保持一致
$ git reset --hard

6、分支操作

# 列出所有本地分支
$ git branch
 
# 列出所有远程分支
$ git branch -r
 
# 列出所有本地分支和远程分支
$ git branch -a
 
# 新建一个分支,但依然停留在当前分支
$ git branch [branch-name]
 
# 新建一个分支,并切换到该分支
$ git checkout -b [branch]

# 切换到指定分支,并更新工作区
$ git checkout [branch-name]

# 合并指定分支到当前分支
$ git merge [branch]
 
# 选择一个commit,合并进当前分支
$ git cherry-pick [commit]
 
# 删除分支
$ git branch -d [branch-name]
 
# 删除远程分支
$ git push origin --delete [branch-name]
$ git branch -dr [remote/branch]

7、克隆仓库

# repo:Git 仓库  directory:本地目录
$ git clone <repo>
$ git clone <repo> <directory>

8、与远程仓库同步

# 增加一个新的远程仓库,并命名
$ git remote add [origin] [url]
 
# 取回远程仓库的变化,并与本地分支合并
$ git pull [remote] [branch]
 
# 上传本地指定分支到远程仓库
$ git push [remote] [branch]
原文地址:https://www.cnblogs.com/Ran-Chen/p/9896519.html