github上传本地文件到远程仓库(空仓库/已有文件的仓库)

今天搞自己本地训练的代码到仓库留个档,结果遇到了好多问题,到腾了半天才搞明白整个过程,留在这里记录一下。

远程空仓库

主要根据官方教程:Adding locally hosted code to GitHub - GitHub Docs

bash 复制代码
#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信息,指定位置关系才可以上传。流程如下:

bash 复制代码
cd ~/test_dir

git 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
相关推荐
Sylvia33.3 小时前
LOL实时数据接入深度解析:从WebSocket到完整数据模型
java·网络·python·websocket·网络协议
梦想不只是梦与想3 小时前
Web 服务器网关协议:ASGI 和 WSGI
服务器·python·fastapi
小弥儿5 小时前
开源 VoiceStudio,声音克隆|配音|有声书一站式本地完成
学习·开源·github
ai小陈5 小时前
PyTorch DataLoader数据加载性能排查:GPU利用率低的实操指南
人工智能·pytorch·python·深度学习·ai·gpu算力
2601_962299248 小时前
Azure python操作系统列表
python·操作系统·azure·虚拟机·存储配置文件
学术 学术 Fun9 小时前
如何用 API 与 Webhook 批量把图表图片转换成 VSDX
python·自动化·api·visio
2601_9621005410 小时前
python包和模块的内容整理
python·模块·导入·虚拟环境·
二进制漫游记10 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
-今昭-11 小时前
《V2V 迁移实战:将 VMware 虚拟机转为 OpenStack 可用 Glance qcow2 镜像》
开发语言·python
2601_9623815811 小时前
【转】Python渗透测试工具:sqlmap
python·渗透测试·sql注入·sqlmap·数据库安全