DarthOpto
DarthOpto

Reputation: 1652

Bash Script - Checking a String Which Has Curly Braces

I have the following portion of a script which is adding a tenant via a curl command and then checking the response. The response is { "tenant": "provisioned" }

Here is my script:

printf "\n** ADDING A TENANT **\n"
TenantResponse=`curl -X POST -H 'Content-Type: application/json' -H 'serviceSharedSecret: sharedsecret' -d '{
"settings": {},
"longName": "QA Test Server",
"tenant_id": "2",
"long_name": "QA Test Server",
"mwa": "string",
"env_overrides": {},
"rough_sizing": "string"
}' "http://${IP_ADDRESS}:8080/rest/1.0/dg/tenants"`
if [[ $TenantResponse == '{ "tenant": "provisioned" }' ]]
  then
    echo "Tenant 2 was added"
    echo '<testcase classname="TenantProvisioning" name="Provision_Tenant_2"/>' >> isoValidationReport.xml
else

    echo "There is a problem provisioning tenant: $TenantResponse"
    echo '<testcase classname="TenantProvisioning" name="Provision_Tenant_2">' >> isoValidationReport.xml
    echo '<failure message="There is a problem provisioning tenant" type="failure"/>' >> isoValidationReport.xml
    echo '</testcase>' >> isoValidationReport.xml
    error_count=$((error_count + 1))
fi

I have tried my [[ $TenantResponse == '{ "tenant": "provisioned" }' ]] with double quotes around the curly braces, single quotes as you can see above as well as no quotes. Seems like nothing is working.

Upvotes: 1

Views: 782

Answers (3)

that other guy
that other guy

Reputation: 123560

As the comments suggest, this is most likely due to a carriage return or possibly a trailing space. That's how fragile this approach is.

The string with curly braces is actually JSON, and should be treated as such:

if [[ $(jq '.tenant == "provisioned"' <<< "$TenantResponse") == "true" ]]
then
  echo "the 'tenant' field has the value 'provisioned'"
else
  echo "it doesn't"
fi

This would make it robust against formatting and future proof it against changes:

{ "tenant": "provisioned" }
{"tenant":"provisioned"}
{"tenant":"provisioned", "year": "2016"}
{"tenant":"unavailable", "previous": "provisioned"}

Upvotes: 4

DarthOpto
DarthOpto

Reputation: 1652

I changed my if statement to look for the word provisioned in the response. Like this if [[ $TenantResponse == *"provisioned"* ]]

This worked.

Upvotes: 0

Matei David
Matei David

Reputation: 2362

Try passing the curl output through tr -dc '[:print:]'. This will remove any non-printable characters, including \r. This will also remove \n, but you might not care about that do to the check.

Upvotes: 0

Related Questions