Punter Vicky
Punter Vicky

Reputation: 16982

how to reference a groovy variable within sh command

How I can I reference groovy variable within sh command?

Script1.groovy: 23: unexpected token: $ @ line 23, column 24. sh(script:zip -r ${BUILD_TAG}.zip src/*.py)

Command

sh(script:zip -r ${BUILD_TAG}.zip src/*.py)

Upvotes: 1

Views: 255

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28739

You need double quotes (") to interpolate variables within strings in Groovy. Your updated step method sh would then have a value of "zip -r ${BUILD_TAG}.zip src/*.py" for the Map passed as the argument, and would appear fully as:

sh(script: "zip -r ${BUILD_TAG}.zip src/*.py")

However, with the installation of the Pipeline Utility Steps Plugin, you can invoke the native bindings step method to zip the file:

zip(zipFile: "${BUILD_TAG}.zip",
    dir: 'src',
    glob: '*.py')

which would be more compatible and stable than the sh step method. For example, if your pipeline is executing on an agent where the zip executable is not named zip, is not directly in your path, does not accept * globbing, or does not accept -r as a valid flag (or possibly -r triggers undesired behavior), then your sh step method will be unsuccessful. However, the native bindings step method for zip will ensure your desired behavior is achieved regardless of environment, platform, etc.

Upvotes: 3

Related Questions