按照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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/506123.html
標籤:其他
