Home > Blockchain >  Jenkins Execute shell if then statement fails with `Bad substitution`
Jenkins Execute shell if then statement fails with `Bad substitution`

Time:04-06

I need an if statement in Jenkins Execute Shell, but it always fails on the same line, regardless of what’s there. I’m trying to do something like this:

if [ " ${BuildVariants[*]} " =~ " VariantA " ]; then
    # fails on this line even this line is just a comment
    variant_config=""
fi

it fails when I try to assign a variable there, fails when I try to echo "anything", fails even on comment (as example above)

Reason: Bad substitution

Note: There's anything specified in Configure System, so it should be using default Bash.

What the problem might be?

CodePudding user response:

I don't think =~ works inside of [ ... ] -- use [[ ... ]] instead.

Shellcheck is a great tool for find these types of things; it would show that you've hit SC2074.

re:

fails on this line even this line is just a comment

You cannot have an "empty" then block. You can use just : as code to be executed:

if [[ "$foo" == "bar" ]]; then
:
fi

Next idea: get your code to run in a shell script, then put the code up in Jenkins. You will probably need to mock up some of the Jenkins-supplied input to do that, but it takes one more moving part out of the equation. If the code runs from the command line and doesn't in Jenkins, then you need to start looking for Jenkins-specific causes, like maybe it's being run in a csh instead of Bash (I see you mention this specific possibility already, but maybe there's something else like it -- I don't know Jenkins, sorry).

CodePudding user response:

So the problem was that I supposed Jenkins was giving me an array, but it was giving me a string. (I used with Extended Choice Parameter, with multiple choices).

So the condition should've been [[ "$BuildVariants" == *"VariantA"* ]].

  • Related