Issue
CASE1:when running following shell script inside Jenkins pipeline:
pipeline
{
agent any
stages
{
stage('image')
{
steps {
script {
sh ( returnStdout: true,
script: ''' #!/bin/bash
if [[ 56 > 10 ]]
then
echo 'The variable is greater than 10.'
fi
'''
) }
}
}
}
}
the above throws an exception:
/var/lib/jenkins/workspace/test-job@tmp/durable-f9ee86ef/script.sh: 2: [[: not found
CASE2: But following pipeline works perfectly fine:
pipeline
{
agent any
stages
{
stage('image')
{
steps {
sh '''#!/bin/bash
VAR=56
if [[ $VAR -gt 10 ]]
then
echo "The variable is greater than 10."
fi
'''
}
}
}
}
kindly please explain to me why the same shell script works in the above CASE2 while it fails in CASE1?
Solution
First script starts with
script: ''' #!/bin/bash
Note that there is a space between '''
and #
. Only if the first two bytes of a script are #!
, this pattern is recognized and defines the shell to use. If it is anything else, including <space>#!
, it is not recognized and the default shell is used. And unless that default shell is bash, [[
is not valid. In POSIX shells, only [
is valid.
The reason why the second script works correctly is because there is no space between '''
and #
.
Answered By - Mecki
Answer Checked By - Robin (JavaFixing Admin)