初始化一个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仓库和远程仓库同步了。