今天搞自己本地訓練的代碼到倉庫留個檔,結果遇到了好多問題,到騰了半天才搞明白整個過程,留在這里記錄一下。
遠程空倉庫
主要根據官方教程:Adding locally hosted code to GitHub - GitHub Docs
#1. cd到你需要上傳的文件夾,我這里路徑是~/test_dir
cd ~/test_dir#2. git init,注意這里!很多git init會直接創建master而不是main,建議用main保持統一
git init -b main### 注意在add和commit之前是沒有branch和status的,因為這時我們還沒有本地的文件進入到類似于一個緩沖區域stage,大概意思是 remote repository <- stage area <- local file。#3. 常規操作了上傳 commit
git add .
git commit -m "init"# 在操作之后我們再通過git branch和git status就可以查看到本地的branch和status了。
# 之后就是在github新建一個倉庫,這時候注意一定要是空的,不要添加readme等文件,不然就會出問題。官方文檔也寫了,到騰半天之后我才看見gan:
# Create a new repository on GitHub. To avoid errors, do not initialize the new
# repository with README, license, or gitignore files. You can add these files
# after your project has been pushed to GitHub.#4. 遠程連接空倉庫,這種情況就是說和github中的倉庫遠程連接了
# push/fetch都指定好了,因為github中的倉庫是空的,所以直接push就可以上傳,
# github創建的branch和本地branch名稱一致,這也是為什么在git init時候用main比較好,如果是master,在github里面也是master。git remote add github_repo <REMOTE-URL(SSH/HTTPS url)>#5. list一下已有的所有連接的github遠程倉庫
git remote -v#6. push上傳
git push github_repo main
下面是我的嘗試過程:
遠程倉庫已經有文件
這個是浪費了我一下午的問題,因為對git整個系統不太了解,所以一直push不上去,一直reject,后來明白是思路錯了。因為倉庫已經存在branch的情況下,我們需要先把遠程文件pull到本地再建立建立本地branch和遠程倉庫branch的連接/track信息,指定位置關系才可以上傳。流程如下:
cd ~/test_dirgit init -b main# 在這里可以先連接遠程倉庫然后git pull下來
git remote add github_repo <REMOTE-URL(SSH/HTTPS url)># 常規操作了上傳 commit
git add .
git commit -m "init"# 先git pull一下下載倉庫所有的branch到本地
git pull # 指定local branch連接哪一個遠程branch,這里我們保持一致用main
git branch --set-upstream-to=github_repo/main main# 再git pull下載對應的branch內容,大概率需要
git pull --no-rebase --allow-unrelated-histories# 再push就ok了
git push