2

I have a very simple bash script with three commands.

The first command strips the first word off of the last git commit, the second command attempts to make a POST call to an api endpoint, with that same variable as part of the call, and the third command just prints that variable, to ensure it was working properly. See the code below

SOMETHING=$(git log -1 --pretty=%B | head -n1 | sed -e 's/\s.*$//' | cut -d ' ' -f1)
curl -X POST \
  http://www.someurl.com/ \
  -H 'Cache-Control: no-cache' \
  -d '{"item":"$SOMETHING"}'
echo "variable was $SOMETHING"

When I run that bash script, I get a response from the service saying that "item was not set properly" in XML, however it does correctly echo the correct variable. So I know that first line is working. If I copy that curl command and paste it into bash, replacing $SOMETHING with the actual value, it works fine.

Josh Beckwith
  • 1,432
  • 3
  • 20
  • 38

1 Answers1

5

Single quotes do not expand the $variables inside them. Try

'{"item":"'"$SOMETHING"'"}'

instead. Brief explanation:

  • '{"item":"' is a string delimited by single quotes that contains double quotes
  • "$SOMETHING" is a string delimited by double quotes, that expands the variable $SOMETHING
  • '"}' is again a ''-delimited string that contains double quotes
  • Simply writing those strings in a row without gaps is string concatenation

In this way, you get your variable expansion, but don't have to insert any backslashes to escape the double quotes.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93