【小白教程】如何从0开始配置本地git连接gitlab

为了配置本地git连接到gitlab,查了不少资料,很多资料都说的不清不楚的,今天我自己终于搞清楚了,把教程写下来给有需要的人。

要从零开始配置本地Git与GitLab的连接,请按照以下步骤进行操作:

  1. 安装Git:如果还没有安装Git,请在计算机上安装它。可以从Git官方网站(https://git-scm.com/downloads )下载Git安装程序,并按照安装指南进行操作

  1. 在GitLab上创建一个账户:如果您还没有GitLab账户,请在GitLab官网(https://gitlab.com/users/sign_in)上创建一个账户。

  1. 创建一个新的Git仓库:登录到您的GitLab账户,然后在页面上创建一个新的Git仓库。请注意Git仓库的名称和位置,因为这些信息将用于配置本地Git。

  1. 在本地计算机上设置Git:在计算机上创建个文件夹,右键打开Git Bash终端,并输入以下命令以设置您的Git用户名和电子邮件地址:

git config --global user.name "Your Name"
git config --global user.email "youremail@example.com"
  1. 生成SSH密钥:输入以下命令以生成SSH密钥:

ssh-keygen -t rsa -C "youremail@example.com"

您将被提示输入一个文件名和密码。您可以保留默认文件名和密码,也可以选择自己的文件名和密码。

  1. 添加SSH密钥到GitLab:使用以下命令将SSH密钥添加到GitLab:

cat ~/.ssh/id_rsa.pub

将在屏幕上看到SSH密钥。复制并粘贴到GitLab账户的SSH密钥部分。

  1. 克隆Git仓库:在本地计算机上打开Git Bash终端,并输入以下命令以克隆Git仓库:

git clone git@gitlab.com:<your_username>/<your_repository>.git

<your_username><your_repository>替换为您在步骤3中创建的Git仓库的用户名和仓库名称。

  1. 进入Git仓库:使用以下命令进入Git仓库:

cd <your_repository>
  1. 将更改推送到Git仓库:在本地计算机上进行更改后,使用以下命令将更改推送到Git仓库:

git add .
git commit -m "commit message"
git push origin master

其中,“commit message”是您的提交消息。

现在您已经成功地将本地Git与GitLab连接起来,可以开始使用Git进行版本控制并将代码推送到GitLab仓库。


在执行第9步操作的时候,如果报错:

On branch master
nothing to commit, working tree clean
To git@gitlab.com:<your_username>/<your_repository>.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'git@gitlab.com:<your_username>/<your_repository>.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.

代表您本地的分支与远程分支的提交历史不一致,所以需要先将远程分支的更改合并到本地分支,然后再将本地更改推送到远程分支。

要解决这个问题,请按照以下步骤操作:

  1. 运行以下命令拉取远程分支的更改:

git pull origin master

这将合并远程分支的更改到您本地的分支。

  1. 如果在合并过程中出现冲突,请解决冲突并提交更改。

  1. 然后再次运行以下命令将更改推送到远程分支:

git push origin master

这样就能够成功地将更改推送到远程分支了。


如果以上还报错,如:

! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@gitlab.com:<your_username>/<your_repository>.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

这个错误提示表明,远程分支比您本地分支更新,因此在推送更改之前,您需要先将远程分支上的更改合并到本地分支中。

为了解决此问题,您可以执行以下操作:

  1. 运行以下命令来拉取远程分支的更改:

git pull --rebase origin master

这将从远程分支下载并合并最新的更改,并使您的本地分支保持最新状态。

  1. 如果在合并过程中出现冲突,请解决冲突并提交更改。

  1. 然后再次运行以下命令将更改推送到远程分支:

git push origin master

就可以解决问题了!