Search code examples
shelljenkinsgroovyjenkins-pipelinesh

Assign groovy variable to process ID inside shell command


From the pipeline, I am simple trying to set my emulators process ID to my variable EMULATOR_PID inside shell script like this:

def EMULATOR_HOME = 'C:/Users/USER/AppData/Local/Android/Sdk/emulator'
def EMULATOR_PID

pipeline {
 agent any

 stages {
    stage('Start emulator') {
        steps {
        sh "$EMULATOR_HOME/emulator -avd Pixel_2_API_29 -port 5554 -wipe-data & $EMULATOR_PID=\$!"
      }
}

In the next stage I am trying to kill that process like so:

stage('Kill process') {
  steps {
    sh "kill $EMULATOR_PID"
}

When i start the build I am getting the following error output:

+ null=5749 <------ EMULATOR_PID
+ C:/Users/USER/AppData/Local/Android/Sdk/emulator/emulator -avd Pixel_2_API_29 -port 5554 -wipe- 
data
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Kill processes)
[Pipeline] sh
+ kill null <------- "null" IS MY EMULATOR_PID
C:/Users/USER/AppData/Local/Jenkins/.jenkins/workspace/Android Test Pipeline@tmp/durable- 
d7aac378/script.sh: line 1: kill: null: arguments must be process or job IDs

How do I correctly assign EMULATOR_PID variable to my emulators process ID here?


Solution

  • You can use this options:

    sPID= sh (
          script: "$EMULATOR_HOME/emulator -avd Pixel_2_API_29 -port 5554 -wipe-data & echo \$!;",
          returnStdout: true
        ).trim()
    

    You may need to work a little on variable sPID to get a clean number of it