从命令行开始使用 Git

Azure DevOps Services | Azure DevOps Server 2022 | Azure DevOps Server 2020

本指南介绍如何使用命令行在 Azure Repos 中共享 Git 存储库中的代码。

下面的说明使用 Linux 和 macOS 上使用的默认 bash shell,但 Git 命令可在任何 shell 中使用,包括 Git for Windows 中的 Git Bash。

先决条件

  • Azure DevOps 中的组织。 如果你没有组织,可免费注册一个。 每个组织都包含免费、无限制的专用 Git 存储库。

下载和安装 Azure CLI 并添加 Azure DevOps 扩展

  1. 安装 Azure CLI。 必须至少安装 v2.0.49,可使用 az --version 命令进行验证。

  2. 添加 Azure DevOps 扩展 az extension add --name azure-devops

  3. 运行 az login 命令。

    如果 CLI 可以打开默认的浏览器,则它会打开该浏览器并加载登录页。 否则,你需要打开一个浏览器页面,在浏览器中导航到 https://aka.ms/devicelogin 后,按照有关命令行的说明输入授权代码。 有关详细信息,请参阅 Azure CLI 登录页

  4. 要实现无缝命令,请在配置中将组织和项目设置为默认值。

    az devops configure --defaults organization=https://dev.azure.com/contoso project=contoso

下载并安装 Git

Windows

下载并安装 Git for Windows,其中包括用于轻松连接到 Azure Repos 的 Git 凭据管理器

macOS

使用 Homebrew 安装和设置 Git。

brew install git

Linux 和 Unix

使用发行版的程序包管理系统来下载并安装 Git。 例如,在 Ubuntu 上为:

sudo apt-get install git

有关 Linux 发行版的最新说明,请参阅安装命令列表

创建本地存储库

为代码创建本地 Git 存储库。 如果代码已在本地 Git 存储库中,则可跳过此步骤。

  1. 在命令行上导航到代码所在的文件夹:

    cd /home/fabrikam/fiber
    
  2. 在计算机上创建用于存储代码的 Git 存储库。 下一部分会将此存储库连接到 Azure Repos。

    git init .
    
  3. 将代码提交到本地 Git 存储库。

    git add --all
    git commit -m "first commit of my code"
    

在 Azure Repos 中创建 Git 存储库

  1. 在 Azure Repos 中为代码新建 Git 存储库。

    az repos create --name FabrikamApp
    
  2. 从 JSON 输出中的 remote URL 属性中复制克隆 URL。

    $ az repos create --name FabrikamApp
    
    [
     {          
         "defaultBranch": null,
         "id": "fa3ee42f-519d-4633-8e31-4a84de343ca3",
         "isFork": null,
         "name": "FabrikamApp",
         "parentRepository": null,
         "project": {
           "abbreviation": null,
           "description": "This is the pipeline project for github repo",
           "id": "fa3ee42f-519d-4633-8e31-4a84de343ca4",
           "lastUpdateTime": "2019-04-09T08:32:15.977Z",
           "name": "Fabrikam",
           "revision": 255,
           "state": "wellFormed",
           "url": "https://dev.azure.com/fabrikops2/_apis/projects/fa3ee42f-519d-4633-8e31-4a84de343ca4",
           "visibility": "public"
         },
         "remoteUrl": "https://dev.azure.com/fabrikops2/Fabrikam/_git/FabrikamApp",
         "size": 0,
         "sshUrl": "fabrikops2@vs-ssh.visualstudio.com:v3/fabrikops2/Fabrikam/FabrikamApp",
         "url": "https://dev.azure.com/fabrikops2/fa3ee42f-519d-4633-8e31-4a84de343ca4/_apis/git/repositories/fa3ee42f-519d-4633-8e31-4a84de343ca3",
         "validRemoteUrls": null
       }
     ]
    
  3. git remote 命令中使用复制的克隆 URL 将本地存储库连接到 Azure Repos 中的 Git 存储库:

    git remote add origin https://dev.azure.com/fabrikops2/Fabrikam/_git/FabrikamApp
    

推送代码

推送代码之前,先使用凭据管理器SSH 设置身份验证,然后再继续。

git push origin main

后续步骤