在github上新建了一个repository, 在新建的时候,选择“Initialize this repository with:” 下面的"Add .gitignore"和"Choose a license"。这样新建完的repository下边会有两个文件 - .gitignore和LICENSE,也就是github上的repository是非空的。
然后我想把本地的一个已有的项目通过如下方式初始化,然后上传,会报错。
1. 本地项目没有初始化成本地repository,需要像下边这样初始化以下
git init
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/xxx/test.git
git push -u origin main
2. 本地项目已经初始化成一个本地的git repository,执行下边的命令上传
git branch -M main
git remote add origin https://github.com/xxx/test.git
git push -u origin main
报错如下,提示远端repository有文件,但是本地没有。
$ git push -u origin main
To https://github.com/xx/test.git
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'https://github.com/xx/test.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.
找了好久没有找到的好的解决方式,最后直接使用-f 参数。这样就可以上传成功了,下次再上传就不会有类似的问题了。
感觉这种解决方式比较粗暴, 如果有其他更好方式,请在评论区留言:
$ git push -u origin main -f
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 8 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (4/4), 273 bytes | 91.00 KiB/s, done.
Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
To https://github.com/xx/test.git
+ 7ad14b1...d284f2d main -> main (forced update)
Branch 'main' set up to track remote branch 'main' from 'origin'.