初始化本地项目
首先执行git init 进行本地项目的初始化。
$ git init
Initialized empty Git repository in D:/xxx/xxx/.git/
初始化成功后在项目下会新增.git 目录。
关联远程仓库
执行下面语句关联仓库(地址使用https和ssh格式都可以)。
git remote add origin git@github.com:xxx/xxx.git
添加访问权限
如果访问git出现下面的报错,检查网络没有问题的话,可能是因为遗漏了添加公钥。
$ git pull
fatal: unable to access 'https://github.com/username/xxx.git/': OpenSSL SSL_read: Connection was reset, errno 10054
$ git pull
fatal: unable to access 'https://github.com/username/xxx.git/': Failed to connect to github.com port 443 after 21067 ms: Timed out
执行下面语句生成本机公私钥。
$ ssh-keygen -t rsa -C "youremail@example.com"
过程中的提示建议一路回车,完成生成后进入C盘下的.ssh目录,找到公钥文件,打开并复制里面内容。 打开git个人设置,找到SSH and GPG keys,把公钥添加到SSH keys。添加完成后在本机执行下面语句测试是否授权成功。
$ ssh -T git@github.com
The authenticity of host 'github.com (20.205.243.166)' can't be established.
ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])?
输入:yes,回车后提示已经授权成功。
Warning: Permanently added 'github.com' (ED25519) to the list of known hosts.
Hi ParoPan! You've successfully authenticated, but GitHub does not provide shell access.
添加修改内容到暂存区并提交
使用git add <file> 命令将需要提交的文件暂存到工作区。对于需要过滤的文件(夹),可以在.gitignore文件里配置。 使用git commit -m <message> 将工作区内容提交到分支。
推送到远程仓库
执行git pull origin main 尝试推送代码远程仓库,提示需要先pull远程代码。 进行pull操作却报错了。
$ git pull origin main
From https://github.com/username/xxx
\* branch main -> FETCH_HEAD
fatal: refusing to merge unrelated histories
这时报错是因为git的远程仓库也有提交历史(比如创建仓库后修改了README.md),此时远程仓库和本地仓库是两个不同版本分支,命令加上–allow-unrelated-histories可以进行强制合并。
$ git pull origin main **--allow-unrelated-histories**
From https://github.com/ParoPan/eblog
\ * branch main -> FETCH_HEAD
Merge made by the 'ort' strategy.
README.md | 9 +++++++++
1 file changed, 9 insertions(+)
create mode 100644 README.md
最后再次push成功。
$ git push -u origin main
Enumerating objects: 77, done.
Counting objects: 100% (77/77), done.
Delta compression using up to 8 threads
Compressing objects: 100% (43/43), done.
Writing objects: 100% (76/76), 5.97 KiB | 1.49 MiB/s, done.
Total 76 (delta 10), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (10/10), done.
To https://github.com/xxx/xxx.git
ed428e9..722c7c4 main -> main
branch 'main' set up to track 'origin/main'.
查看git上远程仓库,看到最新提交记录。
|