新建Github仓库并上传本地代码
按照Github的教程 Adding a local repository to GitHub using Git
1. 创建空的Github仓库
创建远程仓库 🔗 ,注意不要勾选,如果勾选会生成一笔提交,如果本地仓库也提交了代码,会导致拉取/推送代码失败。
2. 切换到本地环境,初始化仓库
$ git init -b main
3. 添加本地文件并提交
$ git add . # Adds the files in the local repository and stages them for commit. 若要取消暂存文件,请使用“git reset HEAD YOUR-FILE”。 $ git commit -m "First commit" # Commits the tracked changes and prepares them to be pushed to a remote repository. 要删除此提交并修改文件,请使用 'git reset --soft HEAD~1' 并再次提交和添加文件。
4. 关联本地仓库和远程仓库
$ git remote add origin <REMOTE_URL> # Sets the new remote $ git remote -v # Verifies the new remote URL
5. 推送代码到远程仓库
$ git push -u origin main # Pushes the changes in your local repository up to the remote repository you specified as the origin
如果勾选了 ,执行最后一步,推送本地代码到远程仓库时会报错
error: failed to push some refs to 'github.com:bwz1984/sql2code.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
因此尝试拉取远程代码
$ git pull origin main
终端提示如下
hint: Pulling without specifying how to reconcile divergent branches is hint: discouraged. You can squelch this message by running one of the following hint: commands sometime before your next pull: hint: hint: git config pull.rebase false # merge (the default strategy) hint: git config pull.rebase true # rebase hint: git config pull.ff only # fast-forward only hint: hint: You can replace "git config" with "git config --global" to set a default hint: preference for all repositories. You can also pass --rebase, --no-rebase, hint: or --ff-only on the command line to override the configured default per hint: invocation. fatal: refusing to merge unrelated histories
重点在于最后一句,Git提示fatal: refusing to merge unrelated histories
,原因分析如下
You have a new Git repository with some commits. You then try to pull from an existing remote repo. The merge becomes incompatible because the histories for branch and remote pull are different. Git sees the situation as you trying to merge two completely unrelated branches, and it doesn’t know what to do.
解决方案
$ git pull origin main --allow-unrelated-histories $ git push origin main
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具