首页 > 解决方案 > 如何使用多个 shell 命令设置 Gitlab ci 阶段

问题描述

鉴于此示例 .Net CI 管道配置为 Gitlab

image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build

build:
  stage: build
  script:
      - |
        BUILD_WARNINGS_LOG_FILE="buildWarnings.log";
        
        dotnet build -consoleloggerparameters:"Summary;Verbosity=normal" -m -p:"WarnLevel=5;EnforceCodeStyleInBuild=true" -t:"clean,build" -fl1 "/flp1:logFile=$BUILD_WARNINGS_LOG_FILE;warningsonly";
        
        if [ $? -eq 0 ] && [ $(wc -l < $BUILD_WARNINGS_LOG_FILE) -gt 0 ]
        then
          # do stuff here
        fi

由于语法无效,管道失败。这是因为它不知道有多个 shell 命令要执行。

.sh文件适用于我的本地机器

#!/bin/bash

BUILD_WARNINGS_LOG_FILE="buildWarnings.log";

dotnet build --output build -consoleloggerparameters:"Summary;Verbosity=normal" -m -p:"WarnLevel=5;EnforceCodeStyleInBuild=true" -t:"clean,build" -fl1 "/flp1:logFile=$BUILD_WARNINGS_LOG_FILE;warningsonly";

if [ $? -eq 0 ] && [ $(wc -l < $BUILD_WARNINGS_LOG_FILE) -gt 0 ]
then
  # do stuff here
fi

那么我怎样才能将它正确地嵌入到 Gitlab ci 阶段呢?

标签: shellgitlabcontinuous-integrationyamlgitlab-ci

解决方案


有三种方法可以做到这一点:

  1. 将您的 shell 脚本添加到图像中,以便您可以执行它:(在您的情况下,这需要基于创建新图像mcr.microsoft.com/dotnet/sdk:5.0
image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build

build:
  stage: build
  script:
      - bash /path/to/your/script.sh
  1. 在运行时创建 shell 脚本(只需将脚本回显到 shell 文件并使其可执行)
image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build

build:
  stage: build
  script:
      - echo "BUILD_WARNINGS_LOG_FILE="buildWarnings.log";\ndotnet build\n-consoleloggerparameters:"Summary;Verbosity=normal" -m -p:"WarnLevel=5;EnforceCodeStyleInBuild=true" -t:"clean,build" -fl1 "/flp1:logFile=$BUILD_WARNINGS_LOG_FILE;warningsonly";\nif [ $? -eq 0 ] && [ $(wc -l < $BUILD_WARNINGS_LOG_FILE) -gt 0 ]\nthen\nfi" > my-bash.sh
      - chmod +X my-bash.sh
      - bash ./my-bash.sh
  1. 使用 multi-bash 命令的正确语法。(注意管道后面的破折号)
image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build

build:
  stage: build
  script:
      - |-
        BUILD_WARNINGS_LOG_FILE="buildWarnings.log";
        
        dotnet build -consoleloggerparameters:"Summary;Verbosity=normal" -m -p:"WarnLevel=5;EnforceCodeStyleInBuild=true" -t:"clean,build" -fl1 "/flp1:logFile=$BUILD_WARNINGS_LOG_FILE;warningsonly";
        
        if [ $? -eq 0 ] && [ $(wc -l < $BUILD_WARNINGS_LOG_FILE) -gt 0 ]
        then
          # do stuff here
        fi

推荐阅读