1. Pass a groovy variable to shell
Your sample doesn't work because you are using a string literal with single quotation marks. From Groovy manual (emphasis mine):
Any Groovy expression can be interpolated in all string literals,
apart from single and triple-single-quoted strings.
Try this:
sh "echo 'Hello World. Var=$var'"
Or this:
sh """
echo 'Hello World. Var=$var'
echo 'More stuff'
"""
2. Set a Groovy variable from shell
You can't directly set a Groovy variable from a shell step. This only works in one direction from Groovy to shell. Instead you can set an exit code or write data to stdout which Groovy can read.
Return a single integer
Pass true for parameter returnStatus and set an exit code from the shell script which will be the return value of the sh step.
var = sh script: 'exit 42', returnStatus: true
echo "$var" // prints 42
Return a single string
Pass true for parameter returnStdout and use echo from shell script to output string data.
var = sh script: "echo 'the answer is 42'", returnStdout: true
echo "$var" // prints "the answer is 42"
Return structured data
Pass true for parameter returnStdout and use echo from shell script to output string data in JSON format.
Parse JSON data in Groovy code using JsonSlurper. Now you have a regular Groovy object that you can query.
def jsonStr = sh returnStdout: true, script: """
echo '{
"answer": 42,
"question": "what is 6 times 7"
}'
"""
def jsonData = new groovy.json.JsonSlurper().parseText( jsonStr )
echo "answer: $jsonData.answer"
echo "question: $jsonData.question"