Git分支操作
刚接触Git,分支操作不容易理解到位,特别是远程和本地分支同步。在操作之前要先想清楚,Git是分布式的、去中心化的,本地就可以创建仓库并提交文件。这跟SVN不一样,SVN必须有一个远程仓库,而Git的所谓的远程仓库是人为指定的,如Github、Gitlab等。Git指定远程仓库的好处是数据更安全,便于协作等。
查看分支
git branch // 本地分支列表,带星号为当前所在分支
git branch -r // 远程分支列表
git branch -a // 本地和远程的分支列表
git branch -vv // 本地分支列表与远程的对应关系
创建本地分支
git checkout -b BranchName
设置远程仓库
git remote add origin [远程仓库地址]
本地分支关联到远程分支
git branch --set-upstream-to=origin/remoteBranchName localBranchName
git branch -vv // 查看本地分支和远程分支的关联关系
推送本地分支到远程
git push origin BranchName
# OR
git push -u origin BranchName
-u
OR --set-upstream
参数指定BranchName
分支为默认远程分支,以后使用git push
即可默认推送BranchName
分支。
切换远程分支(远程分支拉到本地)
git checkout -b localBranchName origin/remoteBranchName
这个将会自动创建一个新的本地分支,并与指定的远程分支关联起来。
如果出现提示:
fatal: Cannot update paths and switch to branch 'dev2' at the same time.
Did you intend to checkout 'origin/dev2' which can not be resolved as commit?
表示拉取不成功。我们需要先执行
git fetch
删除本地分支
git branch -d localBranchName
删除远程分支
git push origin --delete remoteBranchName
如果你得到以下错误消息,可能是因为其他人已经删除了这个分支:
error: unable to push to unqualified destination: remoteBranchName The destination refspec neither matches an existing ref on the remote nor begins with refs/, and we are unable to guess a prefix based on the source ref. error: failed to push some refs to 'git@repository_name'
使用以下命令同步分支列表:
git fetch -p
-p 删除不存在于远程的远程绑定关系