本地仓库推送到github

我来教你如何将本地 Git 仓库推送到 GitHub。

完整步骤

第一步:在 GitHub 上创建仓库

  1. 登录 GitHub (https://github.com)
  2. 点击右上角 "+" -> "New repository"
  3. 填写仓库名称(例如:my-project)
  4. 选择 Public 或 Private
  5. 不要勾选 "Initialize this repository with a README"
  6. 点击 "Create repository"

第二步:连接本地仓库到 GitHub

bash 复制代码
# 1. 进入你的项目文件夹
cd my-project

# 2. 如果还没初始化 git,先初始化
git init

# 3. 添加远程仓库地址
git remote add origin https://github.com/你的用户名/仓库名.git

# 例如:
# git remote add origin https://github.com/zhangsan/my-project.git

# 4. 查看远程仓库是否添加成功
git remote -v

第三步:推送代码到 GitHub

bash 复制代码
# 1. 添加所有文件
git add .

# 2. 提交
git commit -m "first commit"

# 3. 推送到 GitHub(首次推送)
git push -u origin main

# 或者如果分支是 master
git push -u origin master

完整示例

bash 复制代码
# 假设你已经有一个项目文件夹
cd ~/my-work

# 初始化 git
git init

# 配置用户信息(如果之前没配置)
git config user.name "Zhang San"
git config user.email "zhangsan@example.com"

# 添加远程仓库
git remote add origin https://github.com/zhangsan/my-work.git

# 添加文件
git add .

# 提交
git commit -m "Initial commit"

# 推送(首次)
git push -u origin main

常见问题解决

问题1:分支名称不匹配

如果 GitHub 默认分支是 main,但本地是 master

bash 复制代码
# 重命名本地分支
git branch -M main

# 然后推送
git push -u origin main

问题2:需要认证

GitHub 现在要求使用 Personal Access Token (PAT) 而不是密码:

生成 Token:

  1. GitHub -> Settings -> Developer settings -> Personal access tokens -> Tokens (classic)
  2. Generate new token (classic)
  3. 勾选 repo 权限
  4. 生成并复制 token(只显示一次)

使用 Token:

bash 复制代码
# 推送时会提示输入用户名和密码
# 用户名:你的 GitHub 用户名
# 密码:粘贴你的 Personal Access Token

问题3:使用 SSH 代替 HTTPS

bash 复制代码
# 1. 生成 SSH 密钥(如果没有)
ssh-keygen -t ed25519 -C "your.email@example.com"

# 2. 复制公钥
cat ~/.ssh/id_ed25519.pub

# 3. 添加到 GitHub: Settings -> SSH and GPG keys -> New SSH key

# 4. 使用 SSH 地址添加远程仓库
git remote add origin git@github.com:用户名/仓库名.git

# 或修改已有的远程地址
git remote set-url origin git@github.com:用户名/仓库名.git

后续推送

首次推送后,以后只需要:

bash 复制代码
git add .
git commit -m "更新说明"
git push

其他常用命令

bash 复制代码
# 查看远程仓库
git remote -v

# 删除远程仓库连接
git remote remove origin

# 修改远程仓库地址
git remote set-url origin <新地址>

# 拉取远程更新
git pull

# 克隆你自己的仓库
git clone https://github.com/用户名/仓库名.git
相关推荐
Dovis(誓平步青云)3 分钟前
《QT学习第五篇:QSS美化界面与API绘图》
开发语言·数据库·qt·学习·时序数据库·开源智能体
数智工坊13 分钟前
周志华《Machine Learning》学习笔记--第十六章--强化学习
笔记·学习·机器学习
阿萨德528号19 分钟前
[特殊字符] CI/CD 流水线搭建实战指南:Spring Boot + GitHub Actions → 服务器自动部署
spring boot·ci/cd·github
知南x22 分钟前
【DPDK例程学习】(1) helloworld
学习·word
YOLO数据集集合24 分钟前
智慧林业航拍图像数据集 | 树木目标检测、病虫害识别、AI林业监测数据集10282
人工智能·深度学习·目标检测·计算机视觉·无人机
Sc Turing25 分钟前
【AI学习0611】
学习
GHL28427109025 分钟前
Trae学习
学习
一锅炖出任易仙25 分钟前
创梦汤锅学习日记day31
学习·ai
csdn小瓯27 分钟前
本周 GitHub 热门项目推荐:Headroom 和 CC Switch
人工智能·github·开源项目
中讯慧通35 分钟前
微型无人机通信模块:低空链路核心,保障飞行与传输全程稳定
服务器·人工智能·机器人·无人机