“git push”未指定分支时的默认行为 技术背景 在使用 Git 进行版本控制时,git push
是常用的命令之一,用于将本地仓库的更改推送到远程仓库。当执行 git push
命令而不指定具体分支时,其行为由 push.default
配置项控制。了解这些默认行为,可以帮助开发者更高效、安全地管理代码。
实现步骤 1. 查看当前配置 2. 设置新的配置 可以针对单个仓库进行配置:
1 git config push.default current
若想对所有仓库应用相同配置,使用 --global
选项:
1 git config --global push.default current
核心代码 push.default
的可能值及含义nothing
不推送任何内容。
1 git config push.default nothing
matching
(Git 2.0 之前的默认值)推送所有名称匹配的分支。即本地和远程两端名称相同的分支都会被推送。
1 git config push.default matching
upstream
将当前分支推送到其上游分支(tracking
是 upstream
的弃用同义词)。
1 git config push.default upstream
current
将当前分支推送到同名的远程分支。
1 git config push.default current
simple
(Git 1.7.11 新增,Git 2.0 起为默认值)类似于 upstream
,但如果上游分支名称与本地分支不同,则拒绝推送。
1 git config push.default simple
其他代码示例 推送当前分支到 origin
在 .gitconfig
中设置别名 1 2 [alias ] pub = "!f() { git push -u ${1:-origin} `git symbolic-ref HEAD`; }; f"
在 ~/.bash_profile
中设置别名 1 2 3 4 5 get_git_branch () { echo `git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/' ` }alias gpull='git pull origin `get_git_branch`' alias gpush='git push origin `get_git_branch`'
Git 2.37.0 新配置 1 git config --global --add --bool push.autoSetupRemote true
创建 git-setpush
脚本 1 2 3 4 5 6 7 #!/bin/bash -eu CURRENT_BRANCH=$(git branch | grep '^\*' | cut -d" " -f2) NEW_PUSH_REF=HEAD:refs/for/$CURRENT_BRANCH echo "setting remote.origin.push to $NEW_PUSH_REF " git config remote.origin.push $NEW_PUSH_REF
在 .bashrc
中添加函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 function gpush () { if [[ "x$1 " == "x-h" ]]; then cat <<EOF Usage: gpush git: for current branch: push changes to remote branch; EOF else set -x local bname=`git rev-parse --abbrev-ref --symbolic-full-name @{u} | sed -e "s#/# #" ` git push ${bname} set +x fi }function gpull () { if [[ "x$1 " == "x-h" ]]; then cat <<EOF Usage: gpull git: for current branch: pull changes from EOF else set -x local bname=`git rev-parse --abbrev-ref --symbolic-full-name @{u} | sed -e "s#/# #" ` git pull ${bname} set +x fi }
最佳实践 初学者 :建议使用 simple
模式,它是最安全的选项,可避免意外推送不需要的分支。团队协作 :明确团队使用的 push.default
模式,确保协作过程中行为一致。避免误操作 :避免使用 matching
模式,特别是在共享仓库中,以防止意外推送未准备好的分支。常见问题 1. 旧版本 Git 如何设置新的默认行为? 可以通过安装新版本的 Git 来使用 simple
等新选项,或者手动设置 push.default
为所需的值。
2. push.autoSetupRemote
有什么作用? 在 Git 2.37.0 中引入,设置为 true
时,在推送时会自动设置远程分支,适用于 push.default
为 simple
或 upstream
的情况。