Home > Software design >  Using shell variables within a Gitlab CI/CD pipeline script?
Using shell variables within a Gitlab CI/CD pipeline script?

Time:12-17

I have a gitlab ci/cd pipeline with the below in it::

my_script:
  stage: stage
  script:
    - cd dir
    - ls -d */ > lines.txt
    - while read line; do cd $line; pwd; cd ..; done < lines.txt

The "dir" can have one or many directories in it, and I want to be able to dynamically CD into them. The problem here is the cd $line. I believe it keeps trying to read in a CI/CD variable of $line, which doesn't exist. But I want it to read the local shell variable of $line, that is set in the while loop.

I tried surrounding it with '$line' as well but didn't work.

CodePudding user response:

Variable $line gets evaluated (to an empty string) before passing to the actual shell at the runner.

You may wrap in quotes the whole command, passing as an argument to shell interpreter:

- sh -c 'while read line; do cd $line; pwd; cd ..; done < lines.txt'

Anyway, programming in Gitlab's yaml is a bad habit. It is better to create a script in your project instead. It is more readable, portable, and error-safe.

  • Related