正文
学习Git的使用还是应该清楚原理,理解加记忆会更可靠
以下直入主题:
❗注意:新建一个空的本地仓库是不能顺利推送到远程仓库的,因为它们没有历史关系。但你可以先把原仓库的.git目录复制到一个空的文件夹内,然后再按照下面的提示做:
- 进入空文件夹内,鼠标右键打开Git Bash
- 执行代码
#查看git仓库状况(工作区文件被删除,等待add操作更新仓库stage区)
git status
#添加文件(在空工作区执行add命令,完成stage区中的delete操作)
git add .
#操作备注
git commit -m "仓库已清空"
#添加远程仓库(已添加可以跳过)
git remote add origin git@github.com:username/repositoryname
#推送到远程仓库
git push -u origin master
做最后一步时,从本地仓库向Github远程仓库推送更新时可能会发生这样的错误:
$ git push -u origin master
To github.com:code-2023/Java.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'github.com:code-2023/Java.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.
这里有条强制推送命令,本义是从历史不相关的本地仓库强制推送到另一个远程仓库,可以使用 --force 参数,而且Github仓库的历史记录如commit次数应该会被重置,就好像向新仓库进行第一次推送一样。
git push --force origin master
但我试了以后,本地空仓库不仅成功推送到了Github,而且仓库的commit记录还在,因为你的空仓库用的是原仓库的.git目录,继承了原仓库的历史。