0

Need help

I am studying bash and gitlab

can't get it to work

gitlab pipeline .gitlab-ci.yml

variables:
    var1: test1
    var2: test2

stages:
  - build


build-job:   
  stage: build   
  script: 
    - |
      bash -s << EOF
      #!/bin/bash
      test1 () {
        echo $var1
        test3=$var1
      }
      test2 () {
        test1
        echo $var2
        echo $test3
      }
      
      test2
      EOF

'''

Got incorrect answer

'''

Executing "step_script" stage of the job script 00:00

$ bash -s << EOF # collapsed multi-line command

test1

test2

Job succeeded

lost variable test3

'''

Just the same bash script test.sh

#!/bin/bash
test1 () {
echo $var1
test3=$var1
   }
test2 () {
test1
echo $var2
echo $test3
     }

test2

'''

$export var1=test1 $export var2=test2

$sh test.sh

got nice answer This is correct:

test1 test2 test1

but yaml construction has lost variable test3 between functions

I know about run test.sh from gitlab ci, but i need to run it in yaml as text How i can do it?

Thank you

1 Answer 1

1

As mentioned in my answer to your previous question, the here-document needs to be quoted. If it is not, the expansion of the variables (and any other expansion) will be carried out by the invoking shell before the bash -c script can run.

It would be best if you also double-quoted each expansion inside the bash -c script.

Therefore:

bash -s <<'END_SCRIPT'
test1 () {
    echo "$var1"
    test3=$var1
}
test2 () {
    test1
    echo "$var2"
    echo "$test3"
}
  
test2
END_SCRIPT

(Note that since you run the script with bash explicitly, there is no need for a #!-line.)

If you do not quote the here-document delimiter at the start of the here-document, the shell started for the purpose of running the bash -c script would replace all variables. Assuming var1 and var2 exists in the environment as the values test1 and test2, the script that would be executed would be the equivalent of the following:

bash -s <<END_SCRIPT
test1 () {
    echo "test1"
    test3=test1
}
test2 () {
    test1
    echo "test2"
    echo ""
}
  
test2
END_SCRIPT
1
  • just quotes and it works. thank you
    – tuytuy20
    Nov 8, 2022 at 19:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .