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
相关推荐
SelectDB15 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
YuePeng18 小时前
写了五年注解的低代码框架,2.0 决定让你连注解都不用写了
github·产品
小白ai18 小时前
从"能 ping 通吗"到"为什么上不了网"——我写了一个网络故障诊断引擎
github
徐小夕20 小时前
jitword 协同文档3.2发布:打造浏览器中最强word编辑器
前端·架构·github
齐翊1 天前
分享一个在 Claude Code 里 [同时] 用多个 ApiKey 的方法
程序员·github·agent
A_Lonely_Cat1 天前
记一次 GitHub 幽灵协作者大清洗:强制重写 Git 历史与穿透 CDN 缓存实践
git·github
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
极光技术熊2 天前
Spring AI 从入门到精通:构建你的 AI 开发知识体系
后端·github