Jenkins Pipeline Environment Variables | Jenkins set environment variables
Youcanalsocaptureoutputofashellcommandasanenvironmentvariable.Keepinmindthatyouneedtousesh(script:cmd,returnStdout:true)formattoforceshsteptoreturnanoutputsoitcanbecapturedandstoredinavariable.Also,ifyouwanttoavoidcapturingthenewlinecharacterthatisusuallypresentintheshellcommandoutput,calltrim()methodtoremoveallwhitespacefromthebeginningandtheendofthecapturedoutput.Listing6.Jenkinsilepipeline{agentanyenvironment{LS="${sh(script:ls-lah,returnStdout:true).trim()}"}stages{stage("EnvVariables"){...
You can also capture output of a shell command as an environment variable. Keep in mind that you need to use sh(script: cmd, returnStdout:true) format to force sh step to return an output so it can be captured and stored in a variable. Also, if you want to avoid capturing the new line character that is usually present in the shell command output, call trim() method to remove all whitespace from the beginning and the end of the captured output.
Listing 6. Jenkinsile
pipeline { agent any environment { LS = "${sh(script:ls -lah, returnStdout: true).trim()}" } stages { stage("Env Variables") { steps { echo "LS = ${env.LS}" } } } }Wrapping sh step with the Groovy string[1] is only needed when you capture command’s output in the environment block of the declarative pipeline. If you don’t do it that way, the pipeline syntax validation fails instantly, saying that it expects string value on the...