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
相关推荐
咖啡の猫3 小时前
Python字典推导式
开发语言·python
曹文杰15190301123 小时前
2025 年大模型背景下应用统计本科 计算机方向 培养方案
python·线性代数·机器学习·学习方法
GoGeekBaird3 小时前
Andrej Karpathy:2025年大模型发展总结
后端·github
Wulida0099913 小时前
建筑物表面缺陷检测与识别:基于YOLO11-C3k2-Strip模型的智能检测系统
python
FJW0208144 小时前
Python_work4
开发语言·python
爱笑的眼睛114 小时前
从 Seq2Seq 到 Transformer++:深度解构与自构建现代机器翻译核心组件
java·人工智能·python·ai
yaoh.wang4 小时前
力扣(LeetCode) 88: 合并两个有序数组 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
CoderJia程序员甲5 小时前
GitHub 热榜项目 - 日榜(2025-12-21)
开源·大模型·llm·github·ai教程
执笔论英雄5 小时前
【RL】slime创建actor的流程
python
吴佳浩 Alben5 小时前
Python入门指南(四)
开发语言·后端·python