今天搞自己本地训练的代码到仓库留个档,结果遇到了好多问题,到腾了半天才搞明白整个过程,留在这里记录一下。
远程空仓库
主要根据官方教程: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