初始化一个git仓库并推送到远程

本文记录了在Ubuntu 18.04系统中初始化git仓库并推送到远程的过程,包括遇到的错误及解决方法。在尝试push时遇到本地与远程仓库不一致的问题,通过拉取远程代码并解决分支关联问题,最终成功完成推送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初始化一个git仓库并推送到远程

系统:ubuntu 18.04
写在前面:
大学自学了git, 工作当中一直也在使用git, 自以为已经非常熟悉git的常用命令了。但今天从在本地init git project 到push 远程的过程中遇到了一些问题,在这里做个总结,以便参考。

1.打开终端,在本地新建一个git仓库

mkdir myProject
cd myProject/
git init (初始化仓库)
Initialized empty Git repository in /home/intel/myProject/.git/

新建仓库后,你就可以复制你的项目到git仓库。

2.本地仓库准备好后,推送本地仓库到远程仓库

cd myProject
git add .
git commit . -m "this is a test file"
git remote add origin https://github.com/RachelRen05/myProject.git (在和远程仓库关联之前,需要你先在远程创建要关联的仓库)
git push origin master (推送到远程仓库)

执行git push时出错了:

To https://github.com/RachelRen05/myProject.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/RachelRen05/myProject.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

这个错误主要是本地仓库和远程仓库不一致导致的,使用git pull将远程代码拉取到本地

3.拉取远程代码到本地

git pull origin master (master是所在的分支名,表示拉取master分支上的内容到本地)

git pull 时又出现了一个错误:

warning: no common commits
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/RachelRen05/myProject
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> origin/master
fatal: refusing to merge unrelated histories

git pull或者git push中都有可能遇到fatal: refusing to merge unrelated histories的问题,这个问题是因为两个分支没有取得关系(master 与 origin master没有关联)。
解决方法:在git操作命令后面加--allow-unrelated-histories

4.重新拉取远程代码到本地仓库

git pull origin master --allow-unrelated-histories

5.重新执行git push将本地仓库推送到远程仓库

git push origin master

这样,就将本地新建的git仓库和远程仓库同步了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值