0

I'm trying to create a shell script which gives a Json block which is used further. The Json block consists of the dynamic components assigned as variables. Below is the code snippet

failCount=$(cat jenkinstestResults.xml | grep -oP '(?<=failCount>)[^<]+') skipCount=$(cat jenkinstestResults.xml | grep -oP '(?<=skipCount>)[^<]+') echo $failCount echo $passCount echo $skipCount TESTS=("$passCount" "$failCount" "$skipCount") IFS='' read -r -d '' jsonBlock <<"EOF" ,{ "type": "divider" }, { "type": "section", "text": { "type": "mrkdwn", "text": "*${Jenkins.jobStatus}*\n*Jenkins Job:* <${Jenkins.buildUrl}|${Jenkins.buildFullDisplayName}[#${Jenkins.buildNumber}])>*" } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Test Status:*\nPassed: ${TESTS[0]},Failed: ${TESTS[1]}, Skipped: ${TESTS[2]}" } ] }" EOF echo $jsonBlock 

In the development environment, the Jenkins variables are resolving properly. But the issue is with the TEST variable whose values are extracted from the XML is not resolving in the final jsonBlock. It's getting printed as it is.

I'm relatively new to the Shell, kindly help.

1

1 Answer 1

0

You read a quoted here-document into your jsonBlock variable. The here-document is quoted because you added quotes around the here-document delimiter at the start (<<"EOF"). Since the here-document is quoted, the shell will not try to expand any variables or other expansions within it.

To expand the TESTS variable, use an unquoted here-document. To avoid expanding things like ${Jenkins.jobStatus} (this would be a syntax error in most shells as variables can't have dots in their names), escape the $ for these.

json=$( cat <<END_JSON , { "type": "divider" }, { "type": "section", "text": { "type": "mrkdwn", "text": "*\${Jenkins.jobStatus}*\n*Jenkins Job:* <\${Jenkins.buildUrl}|\${Jenkins.buildFullDisplayName}[#\${Jenkins.buildNumber}])>*" } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Test Status:*\nPassed: ${TESTS[0]},Failed: ${TESTS[1]}, Skipped: ${TESTS[2]}" } ] } END_JSON ) 

I'm also using cat here for simplicity.

If you want to output this text segment from the variable json, use

printf '%s\n' "$json" 

... making sure to properly double quote the expansion of the variable to not split its value on whitespaces, and to avoid invoking filename globbing on the words within it.

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.