Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkinsfile add if else script?

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
                }
            }
    }
like image 570
M. Antony Avatar asked Oct 12 '18 10:10

M. Antony


People also ask

Can we use if-else in Jenkins pipeline?

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!

How do you write an if-else condition in shell script?

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.

How do I add a choice parameter in Jenkins pipeline?

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.

How do you write Jenkins pipeline script?

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.


Video Answer


1 Answers

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())
    }
}
like image 55
Szymon Stepniak Avatar answered Oct 20 '22 00:10

Szymon Stepniak