I have the following code inside a Jenkins Groovy scripted pipeline:
def time1 = sh(script: 'date -u +"%Y-%m-%dT%H:%M:%S+00:00"', returnStdout: true).trim()
def time1_sec = sh(script: 'date -d "$time1" +%s', returnStdout: true).trim()
sleep(time: 30, unit: 'SECONDS')
def time2 = sh(script: 'date -u +"%Y-%m-%dT%H:%M:%S+00:00"', returnStdout: true).trim()
def time2_sec = sh(script: 'date -d "$time2" +%s', returnStdout: true).trim()
The console logs show that both time1_sec
and time2_sec
get the same value, meaning whichever date/time data I convert into seconds, it returns 1709164800
.
11:35:12 [Pipeline] sh
11:35:13 + date -u +%Y-%m-%dT%H:%M:%S+00:00
11:35:13 [Pipeline] sh
11:35:13 + date -d +%s
11:35:13 [Pipeline] sleep
11:35:13 Sleeping for 30 sec
11:35:43 [Pipeline] sh
11:35:44 + date -u +%Y-%m-%dT%H:%M:%S+00:00
11:35:44 [Pipeline] sh
11:35:45 + date -d +%s
11:35:45 [Pipeline] echo
11:35:45 time1 : 2024-02-29T16:35:13+00:00
11:35:45 [Pipeline] echo
11:35:45 time2 : 2024-02-29T16:35:44+00:00
11:35:45 [Pipeline] echo
11:35:45 time1_sec: 1709164800
11:35:45 [Pipeline] echo
11:35:45 time2_sec: 1709164800
I used the same shell commands in my Linux terminal, I get the results as expected:
#!/bin/bash
# Script name: date-time-2-seconds.sh
time1=$(date -u +"%Y-%m-%dT%H:%M:%S+00:00")
time1_sec=$(date -d "$time1" +%s)
sleep 30
time2=$(date -u +"%Y-%m-%dT%H:%M:%S+00:00")
time2_sec=$(date -d "$time2" +%s)
echo "time1 : ${time1}"
echo "time2 : ${time2}"
echo "time1_sec: ${time1_sec}"
echo "time2_sec: ${time2_sec}"
$ ./date-time-2-seconds.sh
time1 : 2024-02-29T16:52:58+00:00
time2 : 2024-02-29T16:53:28+00:00
time1_sec: 1709225578
time2_sec: 1709225608
What am I doing wrong in Jenkins Groovy script?
String interpolation does not take place in single-quoted strings. You are passing the literal string date -d "$time1" +%s
to the shell, where no variable named time1
is defined.
Instead, you need the Groovy variable time1
to be expanded in a double-quoted string, so that the result is visible to the shell as, for example, date -d "2024-02-29T16:35:13+00:00" +%s
def time1 = sh(script: 'date -u +"%Y-%m-%dT%H:%M:%S+00:00"', returnStdout: true).trim()
def time1_sec = sh(script: "date -d '${time1}' +%s", returnStdout: true).trim()
sleep(time: 30, unit: 'SECONDS')
def time2 = sh(script: 'date -u +"%Y-%m-%dT%H:%M:%S+00:00"', returnStdout: true).trim()
def time2_sec = sh(script: "date -d '${time2}' +%s", returnStdout: true).trim()
Note the shell does not care about the difference between single and double quotes in this case, as the values of time1
and time2
do not require interpolation by the shell.