Git 实用指南
发布时间 2019年4月26日 • 2 分钟 读完 • 353 字Git-实用指南
Git 官网地址:https://git-scm.com/book/zh/v2
config 的三个作用域
git config --local
git config --global
git config --system配置 user.name和user.email
git config --global user.name 'your name'
git config --global user.email 'your_email@domain.com'显示config配置
git config --list --localgit -u
git mv test demo# 打标签
git tag -a v1.1.0 -m "tagging version 1.1.0"
# 删除本地 Tag
git tag -d v1.1.0
# 删除远程 Tag
git push origin :refs/tags/v1.1.0
# 查看 Tag
git taggit log
git log --onelie
git log -n4
git log --all --graph
git log --all --oneline --graph -n4
git log help --web log1.应该在新建分支上做更改的,发现忘记建新分支了,已经在当前分支做了更改,但是还没commit,怎么办?
答:使用git stash,完整操作如下:
# 暂存当前已经产生更改的代码
git stash
# 切换到新(或新建)分支
git checkout -b new_branch
# 取出暂存的代码
git stash pop2.使用git pull会自动merge分支,产生冲突了,怎么办?
常规流程都是,查看冲突文件并编辑,选择自己要的代码保留,删除不要的代码标记,然后再git add 冲突文件,再git commit,最后git push 齐活。
有些时候你想快速解决,不想编辑冲突文件,直接以当前分支的commit为准并解决冲突,这时文件冲突着,直接使用git checkout取消本地的修改,尴尬的事情出现了,checkout失灵了,还会提示error: path '1.text' is unmerged,如果直接以当前commit为准并解决掉冲突,可做如下操作:
# 将「冲突文件」和指定的 commit (这里指 HEAD)同步
git reset HEAD 冲突文件
# 然后放弃当前的更改,并回到 commit 后,冲突前的文件内容
git checkout -- 冲突文件场景重现:
# 当前分支
➜ test-git git:(test-b2) ✗ git log --oneline
2e75765 (HEAD -> test-b2, origin/test-b2) add b2 test
6cb49c7 (test-b1) second commit
2e35c90 first commit
# 冲突文件状态
(base) ➜ test-git git:(test-b2) ✗ git status
On branch test-b2
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: 1.text
no changes added to commit (use "git add" and/or "git commit -a")
# 未解决冲突想切换到其他分支-失败
(base) ➜ test-git git:(test-b2) ✗ git checkout master
1.text: needs merge
error: you need to resolve your current index first
# 直接 checkout 文件-失败
(base) ➜ test-git git:(test-b2) ✗ git checkout 1.text
error: path '1.text' is unmerged你可以这么做:
# reset
(base) ➜ test-git git:(test-b2) ✗ git reset HEAD 1.text
Unstaged changes after reset:
M 1.text
# checkout
(base) ➜ test-git git:(test-b2) ✗ git checkout -- 1.textgit checkout 后面跟branch、tag、commitID时分别切换到对应的分支、标签、和提交的commitID,如果后面跟文件名,如下:
git checkout HEAD~2 demo.py意思是说:将工作目录中的demo.py变更为止倒数第二次提交的demo.py。
接下来继续补充说一下git reset后面常跟的几个参数:
说前,得有一个概念,暂存区stage,工作区work和本地仓库我们称为:local repo
--soft:变动的是local repo的内容--mixed(缺省参数):变动的是local repo和stage--hard:变动的local repo和stage还有work三处位置3.如何把所有本地多次本地commit记录,变为一次commit记录并提交到远程仓库?
答:如果你清楚的知道你进行过几次commit,那么你可以这么做git reset --soft HEAD~3(比如三次),然后再重新写一次commit提交。
或者你可以,通过git log方式查看提交记录,然后通过git reset --soft commitID,将HEAD指向那次提交,后再重新写一次commit并提交。
Q1:想撤回 commit 操作同时保留代码,怎么办?
A1:执行命令 git reset --soft HEAD^
解释:HEAD^ 意思是上一个版本,也可以写成 HEAD~1,如果想撤销两次commit,命令:HEAD~2
参数:
--soft: 不删除工作空间改动代码,撤销commit,不撤销git add .--mixed: 不删除工作空间改动代码,撤销commit,并且撤销git add .,git reset --mixed HEAD^等同于git reset HEAD^--hard: 删除工作空间改动代码,撤销commit,撤销git add .(恢复到了上一次的commit状态)Q2: 只想修改注释?
A2: git commit --amend,进入默认vim编辑器,修改保存即可