新建Github仓库并上传本地代码

按照Github的教程 Adding a local repository to GitHub using Git

1. 创建空的Github仓库

创建远程仓库 🔗 ,注意不要勾选 Add a README file,如果勾选会生成一笔提交,如果本地仓库也提交了代码,会导致拉取/推送代码失败。

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</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

如果勾选了 Add a README file ,执行最后一步,推送本地代码到远程仓库时会报错

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

Original: https://www.cnblogs.com/amos01/p/16671258.html
Author: Amos01
Title: 新建Github仓库并上传本地代码

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/644489/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球