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
相关推荐
bubiyoushang88828 分钟前
解决 Git 访问 GitHub 时的 SSL 错误
git·github·ssl
tonngw2 小时前
【Mac 从 0 到 1 保姆级配置教程 16】- Docker 快速安装配置、常用命令以及实际项目演示
macos·docker·容器·开源·github·docker desktop·orbstack
AI蜗牛之家3 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk3 小时前
python打卡第48天
开发语言·python
海码0075 小时前
【版本控制】Git 和 GitHub 入门教程
git·github
Eiceblue6 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550406 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂6 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP7 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@7 小时前
Python数据分析7
开发语言·python