Skip to main content

Command Palette

Search for a command to run...

Conditional Logic in a Script Section in a Gitlab Pipeline

Updated
2 min readView as Markdown
Conditional Logic in a Script Section in a Gitlab Pipeline

Problem Statement

To check if a variable in a GitLab CI/CD pipeline's script section is not an empty string, you can use standard shell scripting conditional logic.

Approaches

Using Bash/Shell:

The most common and robust way to check for a non-empty string in a Bash/Shell script within your script section is to use the -n operator within an if statement.

Code

your_job:
  script:
    - if [ -n "$MY_VARIABLE" ]; then
    -   echo "MY_VARIABLE is not empty: $MY_VARIABLE"
    - else
    -   echo "MY_VARIABLE is empty."
    - fi

Explanation:

  • if [ -n "$MY_VARIABLE" ]: This checks if the length of the string $MY_VARIABLE is greater than zero. The double quotes around $MY_VARIABLE are crucial to prevent word splitting and globbing issues if the variable contains spaces or special characters.
  • then and else: Standard shell if statement constructs.
  • fi: Closes the if statement.

Alternative (less preferred for general use, but works):

You can also directly compare the variable to an empty string:

Code

your_job:
  script:
    - if [ "$MY_VARIABLE" != "" ]; then
    -   echo "MY_VARIABLE is not empty: $MY_VARIABLE"
    - else
    -   echo "MY_VARIABLE is empty."
    - fi

Important Considerations:

  • Variable Export:

    If MY_VARIABLE is set in a before_script or a preceding script block and you want it available in subsequent lines or jobs, ensure it is exported (e.g., export MY_VARIABLE="value").

  • Shell Environment:

    The specific shell syntax might vary slightly depending on the shell used by your GitLab Runner (e.g., bash, sh, PowerShell). The examples above are for Bash/sh, which are commonly used.