如何将本地 Git 项目同步到 GitHub(基于 Ubuntu 22.04)

步骤 1: 安装 Git 和相关依赖

Git 安装

1
2
sudo apt update
sudo apt install git

验证安装:

1
git --version

步骤 2: 配置 Git 全局设置

设置你的 GitHub 用户名和邮箱,用于 commit 记录。替换为你的实际信息:

1
2
git config --global user.name "siren202101"
git config --global user.email "your_email@example.com"

步骤 3: 生成 GitHub Personal Access Token (PAT)

PAT 用于 HTTPS 认证(相当于密码):

浏览器访问: GitHub tokens
点击 “Generate new token (classic)”。
选择权限:至少勾选 repo(全选推荐)。
设置过期时间(建议 30 天)。
生成后复制 PAT(以 ghp_ 开头),妥善保存。

注意:PAT 不是 GitHub 登录密码,不要泄露。

步骤 4:进入本地目录

1
cd 

步骤 5: 初始化或检查本地 Git 仓库

检查是否已是 Git 仓库

1
git status

如果报错 “not a git repository”,初始化:

1
2
git init

添加所有文件并提交(假设有新文件,如 luci-app-turboacc-mtk/):

1
2
git add .
git commit -m "Initial commit or add new files"

示例输出(如果有新文件夹):

1
2
3
[main 9a1c868] turboacc-mtk
10 files changed, 1019 insertions(+)
...

步骤 6: 添加或检查远程 GitHub 仓库

添加远程(如果不存在):

1
git remote add origin https://github.com/siren202101/kenzok8-screen.git

如果已存在,报错 “remote origin already exists”,则跳过。验证:

1
git remote -v

输出应为:

1
2
origin  https://github.com/siren202101/kenzok8-screen.git (fetch)
origin https://github.com/siren202101/kenzok8-screen.git (push)

步骤 7: 拉取远程内容(避免冲突)

先 fetch:

1
git fetch origin

然后合并主分支(假设主分支是 main,如果是 master 替换):

1
2
git checkout main  # 或 git checkout -b main
git merge origin/main

如果冲突,手动编辑文件后:

1
2
git add <conflicted_files>
git commit -m "Resolved merge conflicts"

步骤 8: 推送本地变化到 GitHub

1
git push -u origin main

提示输入:

Username: siren202101
Password: 你的 PAT(输入时不显示)。

首次推送后,缓存凭证(避免重复输入):

1
git config --global credential.helper store

如果报错 “non-fast-forward”,先拉取:

1
git pull origin main --rebase

步骤 9: 验证同步

1
git log