Conditional statements in the script

Hi folks!

I am trying to implement the following step in my gitlab CI pipeline and running into syntax errors: unexpected end of file

my-ci-step:
  image: 676020893150.dkr.ecr.us-east-1.amazonaws.com/rust:nightly-20201001
  stage: check
  allow_failure: false
  dependencies:
    - install
    - build
  script:
    - export PATH=$PATH:.cargo/bin
    - >
      if [ "$CI_COMMIT_REF_NAME" == "/^staging\/.*/"]; then
        echo "Skipping version check for staging branch"
      else
        RUST_LOG=info [run some shell command]
      fi

I don’t think using rules would work for me since I want to run different scripts based on the branch rather than decide when to run the step or not. Are there suggestions on how to fix/ other ways to do this? Thanks!

For reference, I first looked at this post: if statement - How to use if-else condition on gitlabci - Stack Overflow

Hi @johnprocter

This post might be useful to you, in terms of the syntax.

Also, you might want to use $CI_COMMIT_REF_SLUG rather than ..._NAME.

From your example code it’s not quite clear how you’re intending this job to be structured, but if you can it would be neater to use rules here:

.rules-staging: &rules-staging
    rules:
        - if: '$CI_COMMIT_BRANCH =~ /^staging\/[a-zA-Z0-9-\.]+$/'
          when: on_success
        - when: never

.rules-production: &rules-production
    rules:
        - if: '$CI_COMMIT_BRANCH == '$CI_DEFAULT_BRANCH'
          when: on_success
        - when: never

.my-ci-step: &my-ci-step
  image: 676020893150.dkr.ecr.us-east-1.amazonaws.com/rust:nightly-20201001
  stage: check
  allow_failure: false
  dependencies:
    - install
    - build
  script:
    - export PATH=$PATH:.cargo/bin
    - RUST_LOG=info [run some shell command]

my-ci-step:staging:
  <<: *rules-staging
  <<: *my-ci-step

mymy-ci-step:staging:
  <<: *rules-production
  <<: *my-ci-step
  before_script:
    - RUST_LOG=info [run some shell command]

If you can’t sensibly use before_script, then potentially you could split this job into separate stages.

To clarify:
Using “- >” removes the newline characters in your script, so your 5 lines if-fi block is passed to the shell on a single line. To force a newline when using “- >” you need to insert a blank line. Passing conditional statements and loops on a single line to the shell is fine too, but it requieres some extra semicolons etc.
“- |” on the other hand works as you would expect it.
I find “- >” handy when having to deal with very long, multi-line commands, so you don’t have to worry about the line continuation character “\”.

1 Like