0

I am trying to write a script where the user can pass startDate and endDate via arguments when running the script. Here's my script (saved as test.sh)-

VAR="$(curl -f -X POST -H 'X-API-TOKEN: XXXXXX' -H 'Content-Type: application/json' -d '{"format": "csv", "startDate": $1, "endDate": $2}' 'https://xxx.qualtrics.com/export-responses' | sed -E -n 's/.*([^"]+).+/\1/p')"
echo $VAR

When running the script I type the following -

~/test.sh '"2020-05-13T17:11:00Z","2020-05-13T20:32:00Z"'

The script throws an error.

1 Answers1

0

You're using $1 and $2 inside single quotes, and the shell doesn't expand variables inside single quotes.

Consider, a simplified example:

#!/bin/bash

VAR="$(echo '{"format": "csv", "startDate": $1, "endDate": $2}')"
echo $VAR

If I run that, notice that I get a literal $1 and $2:

$ ./example hi ho
{"format": "csv", "startDate": $1, "endDate": $2}

You need do get those variables outside of single quotes. One option is the following (I've also added the necessary quote literals around the variables:

#!/bin/bash

VAR="$(echo "{\"format\": \"csv\", \"startDate\": \"$1\", \"endDate\": \"$2\"}")"
echo $VAR

Now I get:

$ ./example hi ho
{"format": "csv", "startDate": "hi", "endDate": "ho"}
Andy Dalton
  • 13,993
  • 1
    You should pretty much always put variable references inside double-quotes, e.g. echo "$VAR" instead of just echo $VAR. Also, unless you're doing something else with VAR, skip the VAR=$(cmd); echo "$VAR", and just run cmd directly. – Gordon Davisson Jun 03 '20 at 05:22
  • @GordonDavisson please see the code in the OP. I don't disagree with your suggestions, but I see no need to introduce extraneous changes that could distract from the solution to the problem the OP is facing. – Andy Dalton Jun 03 '20 at 22:25