How to determine the current operating system in a Jenkins pipeline

The workaround I found for this is

try{
   sh(script: myScript, returnStdout: true)
 }catch(Exception ex) {
    //assume we are on windows
   bat(script: myScript, returnStdout: true)
 }

Or a little bit more elegant solution without using the try/catch is to use the env.NODE_LABELS. Assuming you have all the nodes correctly labelled you can write a function like this

def isOnWindows(){
    def os = "windows"
    def List nodeLabels  = NODE_LABELS.split()
    for (i = 0; i <nodeLabels.size(); i++) 
    {
        if (nodeLabels[i]==os){
        return true
        }
   }
    return false
 }

and then

if (isOnWindows()) {
    def osName = bat(script: command, returnStdout: true)   
} else {
    def osName = sh(script: command, returnStdout: true)
}

As far as I know Jenkins only differentiates between windows and unix, i.e. if on windows, use bat, on unix/mac/linux, use sh. So you could use isUnix(), more info here, to determine if you're on unix or windows, and in the case of unix use sh and @Spencer Malone's answer to prope more information about that system (if needed).


I initially used @fedterzi answer but I found it problematic because it caused the following crash:

org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.Launcher is missing

when attempting to call isUnix() outside of a pipeline (for example assigning a variable). I solved by relying on traditional Java methods to determine Os:

def getOs(){
    String osname = System.getProperty('os.name');
    if (osname.startsWith('Windows'))
        return 'windows';
    else if (osname.startsWith('Mac'))
        return 'macosx';
    else if (osname.contains('nux'))
        return 'linux';
    else
        throw new Exception("Unsupported os: ${osname}");
}

This allowed to call the function in any pipeline context.


Assuming you have Windows as your only non-unix platform, you can use the pipeline function isUnix() and uname to check on which Unix OS you're on:

def checkOs(){
    if (isUnix()) {
        def uname = sh script: 'uname', returnStdout: true
        if (uname.startsWith("Darwin")) {
            return "Macos"
        }
        // Optionally add 'else if' for other Unix OS  
        else {
            return "Linux"
        }
    }
    else {
        return "Windows"
    }
}