Adding an existing local project to GitHub with Git

GitHub Docs当中关于这部分的翻译。

在GitHub侧新建一个仓库

不要添加最后的README, license, 以及 gitignore

Create New Repository drop-down

进行托管

  1. 在本地项目的目录下右键打开Git Bash.

  2. 为本地目录初始化一个Git仓库.

    1
    $ git init -b main
  3. 将文件添加到你新建的Git仓库中。即在commit之前先暂存 (stage)。

    1
    2
    3
    $ git add .
    # Adds the files in the local repository and stages them for commit.
    # To unstage a file, use 'git reset HEAD YOUR-FILE'.
  4. 将暂存在本地仓库中的文件Commit出去。

    1
    2
    3
    $ git commit -m "First commit"
    # Commits the tracked changes and prepares them to be pushed to a remote repository.
    # To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
  5. 在GitHub仓库的Quick Setup页面复制远程仓库的URL。

    Copy remote repository URL field

  6. 回到命令行,将将要push到的远程仓库的URL告诉本地仓库。

    1
    2
    3
    4
    $ git remote add origin  <REMOTE_URL> 
    # Sets the new remote
    $ git remote -v
    # Verifies the new remote URL
  7. 将本地仓库push到Github侧的远程仓库。

    1
    2
    $ git push origin main
    # Pushes the changes in your local repository up to the remote repository you specified as the origin

个人遇到的问题

几个文件夹都被顺利commit了。 但是其中的Client文件夹出现了白色的小箭头并且没有办法从github侧直接访问。

image-20211208201335816

(不过用Go to file还是可以access到的:

image-20211208201421998

下载以后发现Client文件夹为空。

原因是该本地文件夹是一个嵌套Git仓库 (nested Git repository)(详见)。 解决方法是删掉Client里面的.git文件夹,然后执行以下命令重新commit就好了 (以Demo1为例):

1
2
$ git rm -r --cached <FILE_NAME>
# <FILE_NAME> would be Demo1, for example
1
2
3
$ git add <FILE_NAME>
$ git commit -m "MSG"
$ git push origin main

可以看到Client侧可以正常访问了。

image-20211208201932428