Alex
Alex

Reputation: 1262

Send data with curl in Bash script: positional argument not working

Total noob in BASH. Trying to learn. I have the following bash script to make an API request:

#!/bin/bash
if [ $1 = "new_event" ]; then
    a='https://www.googleapis.com/calendar/v3/calendars/'
    b=$2
    c='/events?access_token='
    d=$3
    path=$a$b$c$d

    echo $4

  OUTPUT="$(curl -s -H "Content-Type: application/json" $path -d $4 )"
  echo "${OUTPUT}"
fi

Positional arguments are 'new_event', calendarId, access token and json string. If I run the script I get:

BUT, if I copy the echoed json string and replace $4 for it, everything works.

OUTPUT="$(curl -s -H "Content-Type: application/json" $path -d ' {"guestsCanSeeOtherGuests": false, "location": "", "description": "TEST", "reminders": {"useDefault": false}, "start": {"dateTime": "2017-07-06T14:00:00", "timeZone": "America/Sao_Paulo"}, "end": {"dateTime": "2017-07-06T15:00:00", "timeZone": "America/Sao_Paulo"}, "guestsCanInviteOthers": false, "summary": "TEST", "status": "tentative", "attendees": []} ' )"

Any hint why is it not working with the positional argument while it works if I paste it's content?

Thanks!

Upvotes: 1

Views: 353

Answers (1)

alvits
alvits

Reputation: 6758

When you pass the JSON string as a parameter, it assigns the content contained inside the single quote as a whole string but when you pass it to curl it was subjected to word splitting.

To show what it looks like here's a sample script to demonstrate it.

This script will receive the string and pass it to the second script.

#!/bin/bash
./params $1

This second script simulates what curl sees. It will print the number of parameters it receives.

#!/bin/bash
echo $#

Guess what the output is:

27

To fix your issue and make it simpler, drop the outermost quote and quote everything inside the $().

OUTPUT=$(curl -s -H "Content-Type: application/json" "$path" -d "$4" )

Upvotes: 2

Related Questions