i would like to integrate a simple if else script to my Jenkinsfile but i have a little problem :
My Bash Script :
#!/bin/bash
if [ -e /root/test/*.php ];then
echo "Found file"
else
echo "Did not find file"
fi
The Script work very well but if i try to integrate in a stage they dont function :
stage('Test') {
steps {
script {
if [ -e "/root/test/*.php" ];then
echo found
else
echo not found
}
}
}
In Jenkins declarative/scripted pipeline, we can define multiple if-else blocks and use them in the Pipeline as per the use case. Below is the code snipped, which a user can use to define the multiple if-else blocks in Jenkins. sh "echo 'Hello from ${env. BRANCH_NAME} branch!
If specified condition is not true in if part then else part will be execute. To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.
We will first create a sample pipeline project for this. Login to Jenkins, click on New Item, in the next page provide the name of your choice for your pipeline and select the Pipeline and click on Ok. On the configure job page select the This project is parameterized checkbox in the general tab.
To create a simple pipeline from the Jenkins interface, perform the following steps: Click New Item on your Jenkins home page, enter a name for your (pipeline) job, select Pipeline, and click OK. In the Script text area of the configuration screen, enter your pipeline syntax.
Pipeline's script
step expects Groovy script, not Bash script - https://jenkins.io/doc/book/pipeline/syntax/#script
Instead of using script
step you can use sh
step which is designed to execute shell scripts. Something like this (this is just an example):
stage('Test') {
steps {
sh(returnStdout: true, script: '''#!/bin/bash
if [ -e /root/test/*.php ];then
echo "Found file"
else
echo "Did not find file"
fi
'''.stripIndent())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With