user13755987
user13755987

Reputation:

How to setup Gitlab ci stage with multiple shell commands

Given this example .Net CI pipeline configuration for 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

The pipeline fails because of invalid syntax. This is because it doesn't know there are multiple shell commands to execute.

This .sh file works on my local machine

#!/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

so how can I embed it into a Gitlab ci stage correctly?

Upvotes: 1

Views: 4020

Answers (1)

Pezhvak
Pezhvak

Reputation: 10838

There are three ways to do this:

  1. Add your shell script into the image so you can execute it: (in your case that would require creating a new image based on 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. Create the shell script at run-time (just echo the script into a shell file and make it executable)
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. Use the proper syntax of multi-bash command. (note the dash after the pipe)
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

Upvotes: 3

Related Questions