Passing variable from shell script to jenkins

I trigger a shell script from Jenkins, This scripts get date and export it as a environment(Linux) variable $DATE. I need to use this $DATE inside same Jenkins job. I made job as parameter build. Created a string parameter as DATE value as DATE=$DATE. But it is not working.

Please suggest !!


You mention that you are exporting a DATE environment variable in an shell script, which is presumably being started via an "Execute shell" step.

The problem is, once the shell step has completed, that environment is gone — the variables will not be carried over to subsequent build steps.
So when you later try to use the $DATE value — whether in another build step, or as a parameter to another job — that particular environment variable will no longer exist.

What you can do instead is use the EnvInject plugin to export environment variables during a build. Variables set up using this plugin will be available to all subsequent build steps.

For example, you could write the DATE to a properties field in one build step:

echo DATE=$(date +%Y-%m-%d) > env.properties

Then you can add an "Inject environment variables for your job" build step, and enter env.properties in the "Environment Properties File Path" field.

That way, the DATE variable (and anything else in that properties file) will be exported and will be visible to the rest of the build steps.


You could use an assignment statement and sh's returnStdout to get the value in Jenkins without having to write to a properties file.

foo = sh(
  returnStdout: true, 
  script: 'date'
)

Then later on in the Jenkinsfile you can use $foo like any other variable.

EDIT: This is for a pipeline job, not a freestyle job.