文章目录
-
- [1. 背景](#1. 背景)
- [2. 解决方案](#2. 解决方案)
- [3. 传统方式](#3. 传统方式)
- [4. 检查 Git 版本](#4. 检查 Git 版本)
- [5. 相关配置对比](#5. 相关配置对比)
- [6. 查看当前配置](#6. 查看当前配置)
- [7. 小结](#7. 小结)
配置项: push.autoSetupRemote
1. 背景
Git 在推送没有追踪上游的分支时, 会给出一个建议。
git push
fatal: The current branch feature/feature-new has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin feature/feature-new
To have this happen automatically for branches without a tracking
upstream, see 'push.autoSetupRemote' in 'git help config'.
告诉你:可以通过配置让 Git 自动建立追踪关系 ,省去每次手动加 -u。
2. 解决方案
开启 push.autoSetupRemote
需要 Git 2.37 及以上版本
bash
# 全局配置(对所有仓库生效)
git config --global push.autoSetupRemote true
# 仅当前仓库生效
git config push.autoSetupRemote true
配置后的效果:
bash
git switch -c feature-new
git push # 直接成功!自动创建远程分支并建立追踪关系
Git 会自动执行相当于 git push -u origin feature-new 的操作。
3. 传统方式
每次手动指定(传统方式)
bash
git push -u origin feature-new
# 或
git push --set-upstream origin feature-new
4. 检查 Git 版本
bash
git --version
如果版本低于 2.37,autoSetupRemote 不可用,需要先升级 Git:
bash
# macOS (Homebrew)
brew upgrade git
# Ubuntu/Debian
sudo apt update && sudo apt install git
# Windows
# 下载最新版:https://git-scm.com/download/win
5. 相关配置对比
| 配置项 | 作用 |
|---|---|
push.autoSetupRemote |
推送时自动为无上游的分支创建远程分支并追踪 |
push.default |
控制 git push 默认推送哪些分支(simple/current/upstream 等) |
常见搭配
bash
# 推荐组合配置
git config --global push.default simple # 默认值,安全
git config --global push.autoSetupRemote true # 自动建立上游
6. 查看当前配置
bash
# 查看单个配置
git config push.autoSetupRemote
# 查看所有 push 相关配置
git config --get-regexp push
7. 小结
最简单的做法就是执行一次:
bash
git config --global push.autoSetupRemote true
之后新建分支直接 git push 即可,无需再关心上游追踪问题。