远程分支跟踪
跟踪分支(Tracking Branch)是本地分支与远程分支的关联关系。
什么是跟踪分支
跟踪分支设置了上游(upstream)远程分支,使得:
git push自动推送到对应远程分支git pull自动从对应远程分支拉取git status显示与远程分支的差异
远程分支命名
Bash
远程分支格式:<remote>/<branch>
例如:origin/main, origin/feature
设置跟踪分支
Bash
# 方法1:推送时设置(推荐)
git push -u origin feature
git push --set-upstream origin feature
# 方法2:创建分支时设置
git checkout -b feature origin/feature
git checkout --track origin/feature
# 方法3:已有分支设置上游
git branch -u origin/feature
git branch --set-upstream-to=origin/feature
查看跟踪关系
Bash
# 查看分支详细信息
git branch -vv
# 输出示例
feature a1b2c3d [origin/feature] 添加新功能
* main b2c3d4e [origin/main] 主分支
# 查看远程分支
git branch -r
跟踪分支示例
Bash
# 创建跟踪分支
$ git checkout -b feature origin/feature
Branch 'feature' set up to track remote branch 'feature' from 'origin'.
Switched to a new branch 'feature'
# 查看状态
$ git status
On branch feature
Your branch is up to date with 'origin/feature'.
常用操作
| 命令 | 说明 |
|---|---|
| git branch -vv | 查看跟踪关系 |
| git branch -u / | 设置上游分支 |
| git push -u | 推送并设置上游 |
| git checkout --track / | 创建跟踪分支 |
跟踪分支的好处
Bash
无跟踪分支:
git push origin feature
git pull origin feature
有跟踪分支:
git push
git pull
修改跟踪关系
Bash
# 修改上游分支
git branch -u origin/new-feature feature
# 取消跟踪
git branch --unset-upstream feature
克隆时自动跟踪
text
# 克隆仓库时自动创建跟踪
git clone <url>
# main 分支自动跟踪 origin/main
# 克隆后创建其他跟踪分支
git checkout -b dev origin/dev
查看与远程的差异
text
# 本地领先远程
$ git status
Your branch is ahead of 'origin/main' by 2 commits.
# 本地落后远程
$ git status
Your branch is behind 'origin/main' by 3 commits.
# 本地与远程分叉
$ git status
Your branch and 'origin/main' have diverged.
设置跟踪分支后,push/pull 操作更简便。
要点总结
- 跟踪分支建立本地与远程的关联
-u或--set-upstream设置上游分支git branch -vv查看跟踪关系- 有跟踪分支时 push/pull 无需指定远程
- 克隆时自动设置 main 分支跟踪
📝 发现内容有误?点击此处直接编辑