I want to get a last date of weekday, like today-3 if today is Monday or today-1, in Jenkins pipeline script. So I wrote a script like this :
environment {
TODAY_WEEK = "`date %u`" // today is 9/26/2022, so "1"
LAST = "${env.TODAY_WEEK == "1" ? "`date -d '-3 day' %Y%m%d`" : "`date -d '-1 day' %Y%m%d`"}"
}
...
sh( "diff report_${LAST}.json report_${TODAY}.json" )
But when I run this script, LAST
always become date -d '-1 day'
regardless current date.
So I tried to another method :
environment {
TODAY_WEEK = "`date %u`" // today is 9/26/2022, so "1"
LAST = getLastDate(env.TODAY_WEEK)
}
...
def getLastDate(dayOfWeek) {
today = new Date()
if (dayOfWeek.equals("1")) {
last = today - 3
} else {
last = today - 1
}
return last.format("yyyyMMdd")
}
But I got same result - LAST become always date of 'today - 1'. What's wrong with this script?
CodePudding user response:
This pipeline script will help:
pipeline {
agent any
environment {
TODAY_WEEK = sh(returnStdout: true, script: 'date %u')
}
stages {
stage ('Run'){
steps {
script {
today = new Date()
if (env.TODAY_WEEK.toInteger() == 1) {
testLast = today - 3
lastDayofWeek = testLast.format("yyyyMMdd")
echo "${lastDayofWeek}"
}
else {
testLast = today - 1
lastDayofWeek = testLast.format("yyyyMMdd")
echo "${lastDayofWeek}"
}
}
}
}
}
}
Output:
Reason of not correct output of your job
In your pipeline script, the environment variable TODAY_WEEK
is not returning any result and thus the script always fail to invoke the else condition.
You can print the environment variables in Jenkins pipeline using the below:
sh "printenv"