Search code examples
gitlabgitlab-cizshcicd

Unable to set Variable in gitlab-ci.yml


In this abridged version of a gitlab-ci.yaml file. The global variable APP_VERSION can either be filled or left blank. In the case of it being left blank, I want to set the variable to the version value that exists in version_cache/version.txt. If APP_VERSION already contains a version, then it will use that.

variable:
  APP_VERSION: ""

build_image:
  stage: build_image
  before_script:
    - APP_VERSION=if [ -z $APP_VERSION ]; then echo $(cat version_cache/version.txt); else echo $APP_VERSION; fi;

When the runner runs this, I get

bash: eval: line 128: syntax error near unexpected token `then'

The runner uses zsh. I saw an example on SO where a variable is set this way, yet I'm unable to understand the missing syntax.


Solution

  • The issue seems to be that you are trying to assign a value to APP_VERSION, but you are passing the actual code, not the result as you intend to. Add `` to explain to bash that you need the result of the command. As an addition to VonC's answer
    Try changing

    - APP_VERSION=if [ -z $APP_VERSION ]; then echo $(cat version_cache/version.txt); else echo $APP_VERSION; fi;
    

    To

    - APP_VERSION=`if [ -z "$APP_VERSION" ]; then cat version_cache/version.txt; else echo "$APP_VERSION"; fi;`