Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking sh or bat generically from a Jenkins pipeline script

I'm working on a pipeline script that will execute on both Windows and Linux. For both systems, I need to invoke the same command (for example python -V). I can accomplish this with a helper function:

def genericsh(cmd) {
    if (isUnix()) {
        sh cmd
    }
    else {
        bat cmd
    }
}

Then in my Jenkinsfile:

genericsh 'python -V'

This seems to work okay, however it produces extra isUnix noise in the output log for each command executed.

Is there a better way to invoke a command generically across Windows and Linux in a Jenkins pipeline script? If not is there a mechanism for suppressing the isUnix() step tag in the pipeline log?

like image 650
DRH Avatar asked Dec 04 '17 23:12

DRH


People also ask

What is sh command in Jenkins pipeline?

On Linux, BSD, and Mac OS (Unix-like) systems, the sh step is used to execute a shell command in a Pipeline. Jenkinsfile (Declarative Pipeline) pipeline { agent any stages { stage('Build') { steps { sh 'echo "Hello World"' sh ''' echo "Multiline shell steps works too" ls -lah ''' } } } }


1 Answers

You could assign isUnix() to a variable early in your script which would mean that you only see that once, not once per external command.

env.UNIX = isUnix()

then

def genericSh(cmd) {
    if (Boolean.valueOf(env.UNIX)) {
        sh cmd
    }
    else {
        bat cmd
   }
}
like image 121
mjaggard Avatar answered Oct 18 '22 20:10

mjaggard