Git 命令简介
1.创建
1.初始化
git init test # 在test目录生成一个 .git 目录
2.克隆:git clone
git clone <repo> # 克隆仓库
git clone <repo> <directory> # 克隆到指定的目录
git clone https://github.com/robbiehanson/CocoaAsyncSocket.git test2 # 克隆该库到test2文件夹
3.配置:git config
git config --list
git config -e # 针对当前仓库
git config -e --global # 针对系统上所有仓库
git config --global user.name "xxxxx.xx" # 设置提交代码时的用户名
git config --global user.email xxxxx.xx@xxxx.com # 设置提交代码时的用户邮箱
# 如果去掉 --global 参数只对当前仓库有效。
2.基本操作
# 查看文件修改状态
git status # 用于查看上次提交之后是否有对文件进行再次修改
git status -s # 使用 -s 参数来获得简短的输出结果
# 查看文件修改前后的差异
git diff [file] # 显示暂存区和工作区的差异
git diff --cached [file] # 显示暂存区和上一次提交(commit)的差异
git diff [first-branch]...[second-branch] #显示两次提交之间的差异
# 添加文件到暂存区
git add [file1] [file2] ... # 添加一个或多个文件到暂存区
git add [dir] # 添加指定目录到暂存区,包括子目录
git add . # 添加当前目录下的所有文件到暂存区
# 提交到本地
git commit -m [message] # 提交暂存区到本地仓库中
git commit [file1] [file2] ... -m [message] # 提交暂存区的指定文件到仓库区
git commit -a # -a 参数设置修改文件后不需要执行 git add 命令,直接来提交
# 回退版本
git reset [--soft | --mixed | --hard] [HEAD] #--mixed 为默认,可以不用写
git reset HEAD^ # 回退所有内容到上一个版本
git reset HEAD^ hello.php # 回退 hello.php 文件的版本到上一个版本
git reset <Hash> # 回退到指定版本
git reset --soft HEAD~2 # 回退上上一个版本
git reset --hard HEAD # --hard 回到上一次版本,并删除之前的所有信息提交
git reset --hard <Hash> # 回退到指定版本,并删除之前的所有信息提交
# 删除
git rm <file> # 将文件从暂存区和工作区中删除
git rm -f <file> # 强制删除
git rm --cached <file> #从暂存区中删除,工作区保留
# 查看提交历史
git log # 查看历史提交记录
git log --oneline #查看简洁版历史提交记录
git log --graph #查看历史提交记录,开启拓扑图选项
git blame <file> #以列表形式查看指定文件的历史修改记录
#远程操作
git pull <远程主机名> <远程分支名>:<本地分支名>
git pull origin master:brantest #将远程主机 origin 的 master 分支拉取过来,与本地的 brantest 分支合并
git push <远程主机名> <本地分支名>:<远程分支名>
git push origin master:master #将本地的 master分支推送到 origin主机的 master分支
#分支
git branch (branchname) # 创建分支
git checkout (branchname) # 切换分支
git branch -d (branchname) # 删除分支
git merge (branchname) #合并分支
#标签
git tag -a v1.0 # 打上标签
git tag # 查看所有标签
git tag -a <tagname> -m "V1.0" # 指定标签信息
git tag -d v1.1 # 删除标签
git show v1.0 # 查看标签版本所修改的内容
3.合并冲突
git merge (branchname) #如果产生冲突
# 手动解决冲突后
git add . #添加已经解决冲突的文件
git commit #提交结果
4.变基
- 合并多个commit
- 分支合并
git rebase -i HEAD~4 # 合并最近的 4 次提交纪录
git rebase <branchname> # 变基到<branchname>
5.转移分支
git cherry-pick <HashA> <HashB> #将A和B提交转移到当前分支上
git cherry-pick <HashA>..<HashB> #将A到B之间的提交转移到当前分支上(左开右闭)
git cherry-pick <HashA>^..<HashB> #将A到B之间的提交转移到当前分支上(包含A)
例子:
git cherry-pick 22edd0d2b4..fafc141820
#冲突后的操作
#1.修改冲突
#2.add 修改后的文件
git cherry-pick --continue # 继续执行cherry-pick操作
git cherry-pick --abort # 终止cherry-pick操作
git cherry-pick --quit # 退出 Cherry pick,但是不回到操作前的样子,一般遇到cherry失败,就用这个