git常用之已存在的目录转换为一个 GIT 项目并托管到github仓库

git常用之已存在的目录转换为一个 GIT 项目并托管到github仓库

步骤

  1. 将目录初始化为一个 Git 项目
bash 复制代码
 git init
  1. 修改你git 想展示的用户
bash 复制代码
git config user.name xxx
git config user.email  xxx@xxx.com
  1. 创建 .gitignore 文件 文件

  2. 将所有文件放进新的本地 git 仓库

bash 复制代码
git add . 

如果你本地已经有 .gitignore 文件,会按照已有规则过滤不需要添加的文件。如果不想要添加所有文件,可以把 . 符号换成具体的文件名。

  1. 将添加的文件提交到仓库
bash 复制代码
 git commit -m "Initial commit"
  1. 访问 GitHub,创建一个新仓库

注意:为了避免冲突,先不要勾选 README 和 LICENSE 选项

  1. 在生成的项目github主页上,复制仓库地址

    例如:

    git@github.com:xxx/xxx.git

  2. 回到命令行终端界面,将本地仓库关联到远程仓库

bash 复制代码
git remote add origin git@github.com:xxx/xxx.git
git remote -v
  1. 把Git默认分支master修改为main
bash 复制代码
  git branch
* master

Github 把 master 默认分支改为了 main ,我们把本地 Git 配置文件里的 master 改成 main

0) 重命名本地 Git 存储库中的 "master" 分支

bash 复制代码
 git branch -m master main
 git branch

1) Windows 中 Git 的配置文件在 C:\Users<用户名> 下 .gitconfig

修改为:

bash 复制代码
[init]
    defaultBranch = main

2) 直接使用 Git 命令:

bash 复制代码
git config --global init.defaultBranch main
  1. 提交代码到 GitHub 仓库
    设置本地 main 分支与远程 main 分支的追踪关系
bash 复制代码
git branch --set-upstream-to=origin/main main  

git pull 如果报错:
fatal: refusing to merge unrelated histories

则执行

bash 复制代码
git pull origin main --allow-unrelated-histories  

如果报错:Automatic merge failed; fix conflicts and then commit the result.

则执行,使用以下命令强制合并远程分支,并以本地的 文件为准:

bash 复制代码
git pull origin main --allow-unrelated-histories -X ours  
git commit -m "Resolve merge conflict " 
git push origin main  

其他参考

如何在 Git 中将 master 分支重命名为 main

参考URL: https://www.git-tower.com/learn/git/faq/git-rename-master-to-main

相关推荐
CoderJia程序员甲33 分钟前
GitHub 热榜项目 - 日榜(2026-04-14)
人工智能·ai·大模型·github·ai教程
Hical_W1 小时前
告别回调地狱:在 C++ Web 框架中全面拥抱协程
c++·github
别叫我->学废了->lol在线等1 小时前
claudecode的agent定义
前端·chrome·github
研究点啥好呢2 小时前
Github热榜项目推荐 | 学习与贡献是开源的意义
学习·开源·github
鸿蒙程序媛2 小时前
【工具汇总】git 常用命令行汇总
大数据·git·elasticsearch
kiku18182 小时前
keepalived高可用与负载均衡
后端·github·lvs
yyuuuzz2 小时前
独立站搭建:从基础到避坑的实战分享
前端·javascript·github
星浩AI3 小时前
你和 10 倍生产力之间,差的就是它 : claude-howto,用一个周末掌握ClaudeCode
github·claude·vibecoding
虞十三3 小时前
AtomGit 开源入门全攻略:环境搭建 + Git/Docker 实操 + 新手避坑(全平台版)
git·docker·容器
tz_zs3 小时前
【github copilot】 Language model unavailable
语言模型·github·copilot·ai编程