git push 推送更改
git push 命令将本地分支的提交推送到远程仓库。
基本用法
Bash
# 推送当前分支到 origin
git push
# 推送指定分支
git push <remote> <branch>
# 推送到 origin 的 main 分支
git push origin main
推送示例
Bash
# 推送当前分支(已设置上游)
git push
# 推送新分支并设置上游
git push -u origin feature
# 推送所有分支
git push --all origin
# 推送标签
git push --tags
git push origin v1.0
常用选项
| 选项 | 说明 |
|---|---|
| 无选项 | 推送当前分支 |
| -u, --set-upstream | 设置上游分支 |
| --all | 推送所有分支 |
| --tags | 推送所有标签 |
| -f, --force | 强制推送(危险) |
| --dry-run | 预览推送内容 |
推送流程
Bash
本地仓库 → 远程仓库
↓
git push origin main
↓
远程 main 分支更新
推送新分支
Bash
# 创建并推送新分支
git checkout -b feature
git push -u origin feature
# 后续推送简化
git push
推送标签
Bash
# 推送单个标签
git push origin v1.0
# 推送所有标签
git push --tags
# 推送时携带标签
git push --follow-tags
处理推送失败
Bash
# 远程有新提交时推送失败
$ git push
! [rejected] main -> main (fetch first)
# 解决方法1:先拉取再推送
git pull --rebase
git push
# 解决方法2:强制推送(危险!)
git push -f
git push --force
强制推送注意事项
强制推送会覆盖远程历史,可能丢失他人的提交! 只在以下情况使用:
- 个人分支,确认无其他协作
- 本地 rebase 后需要同步
- 清理错误提交历史
Bash
# 更安全的强制推送(检查远程状态)
git push --force-with-lease
推送验证
text
# 预览推送内容
git push --dry-run
# 查看将要推送的提交
git log origin/main..HEAD
推送前建议先 pull 确保同步,避免冲突。
要点总结
git push推送当前分支到上游git push -u origin <branch>推送并设置上游git push --tags推送所有标签- 推送失败时先 pull 再 push
--force-with-lease比--force更安全
📝 发现内容有误?点击此处直接编辑