3

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.

paiego
  • 3,619
  • 34
  • 43

2 Answers2

3

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;`
Tolis Gerodimos
  • 3,782
  • 2
  • 7
  • 14
1

After checking with shellcheck, try:

$(if [ -z "$APP_VERSION" ]; then cat version_cache/version.txt; else echo "$APP_VERSION"; fi;)
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Still getting error: $ APP_VERSION=if [ -z "$APP_VERSION" ]; then cat version_cache/version.txt; else echo "$APP_VERSION"; fi; bash: eval: line 128: syntax error near unexpected token `then' – paiego Jan 26 '22 at 08:11
  • 1
    @paiego Can you try and simplify, just for testing: `if [ "${APP_VERSION}" == "" ]; then...` – VonC Jan 26 '22 at 08:23
  • thanks for the help but I got it working with the Tolis' recommendation. – paiego Jan 26 '22 at 20:12
  • FYI: I was also able to get it working with $(), which is supposed to replace the back ticks '`' eventually: APP_VERSION=$(if [ -z "$APP_VERSION" ]; then cat version_cache/chart_version.txt; else echo "$APP_VERSION"; fi;) – paiego Jan 26 '22 at 21:33
  • @paiego Good call: I already documented the [difference between `$(command)` and ```command``` in shell programming](https://stackoverflow.com/a/24592916/6309) seven years ago. – VonC Jan 26 '22 at 21:50