How to post a multi line json string as body in curl inside bash script

11,820

This worked

curl -H "Content-Type: application/json" -X POST -d "$body" https://dev.cloudapp.net/v1/
Share:
11,820

Related videos on Youtube

user330612
Author by

user330612

Updated on September 20, 2022

Comments

  • user330612
    user330612 over 1 year

    I have the following bash script

    #!/bin/bash
    
    body=$(cat  << EOF
    {
        "CreatedBy":  "$(hostname -f)",
        "Id":  "$(uuidgen)",
        "Type":  "TestAlertType",
        "AlertCategory":  "NonUrgent"
        }
    EOF
    )
    
    
    curl -H "Content-Type: application/json" -X POST -d $body https://dev.cloudapp.net/v1/
    

    But I get invalid json error on post. What am i missing?

    • jordanm
      jordanm over 8 years
      You need to quote your expansion: "$body".
  • TPPZ
    TPPZ about 5 years
    If the content of $body has/needs new lines / carriage returns (e.g. \n), then you need to add IFS=$"\n" before creating $body with cat and EOF otherwise when using $body later on the new lines disappear, no matter if you use double quotes like "$body".