我想得到一个工作日的最后一个日期,就像今天一样--如果今天是星期一还是今天--1,在Jenkins管道脚本中。所以我写了一个这样的剧本:
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" ) 但是当我运行这个脚本时,无论当前日期如何,LAST总是变成date -d '-1 day'。于是我尝试了另一种方法:
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")
}但我也得到了同样的结果--最后一次成为“今天-1”的日子。这个剧本怎么了?
发布于 2022-09-26 05:11:47
此管道脚本将有助于:
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}"
}
}
}
}
}
}输出:

导致作业输出不正确的原因
在您的管道脚本中,环境变量TODAY_WEEK没有返回任何结果,因此脚本总是无法调用else条件。
您可以使用以下方法在Jenkins管道中打印环境变量:
sh "printenv"https://stackoverflow.com/questions/73848914
复制相似问题