Passing variables extracted from shell in Jenkinsfile

Here is what I do to get the number of commits on master as a global environment variable:

pipeline {

    agent any

    environment {
        COMMITS_ON_MASTER = sh(script: "git rev-list HEAD --count", returnStdout: true).trim()
    }

    stages {

        stage("Print commits") {
            steps {
                echo "There are ${env.COMMITS_ON_MASTER} commits on master"
            }
        }
    }
}

You can use the longer form of the sh step and return the output (see Pipeline document). Your variable should be defined outside the stages.