executing a curl request through bash script
11,157
#!/usr/bin/env bash
rvmcurl() {
local url
url="http://192.168.1.101:8080/sitewhere/${1#/}"
shift || return # function should fail if we weren't passed at least one argument
curl -XPOST "${rvm_curl_args[@]}" "$url" "$@"
}
i=1 # for testing purposes
rvm_curl_args=(
-H 'accept:application/json'
-H 'content-type:application/json'
-H 'x-sitewhere-tenant:sitewhere1234567890'
--user admin:password
)
data=$(jq -n --arg hardwareId "$i" '
{
"hardwareId": $hardwareId,
"siteToken": "4e6913db-c8d3-4e45-9436-f0a99b502d3c",
"specializationToken": "82043707-9e3d-441f-bdcc-33cf0f4f7260"
}')
rvmcurl /api/devices -d "$data"
Note:
-
Commands, or command fragments intended to be parsed into multiple words, should never be stored in strings. Use an array or a function instead. Quotes inside such strings are not parsed as syntax, and instead (when parsed without
eval
, which carries its own serious risks and caveats) become literal values. See BashFAQ #50 for a full explanation. - Use a JSON-aware tool, such as
jq
, to ensure that generated data is legit JSON. - Fully-qualifying paths to binaries is, in general, an antipattern. It doesn't result in a significant performance gain (the shell caches PATH lookups), but it does reduce your scripts' portability and flexibility (preventing you from installing a wrapper for
curl
in your PATH, in an exported shell function, or otherwise). - All-caps variable names are in a namespace used for variables with meaning to the shell and operating system. Use names with at least one lowercase character for your own variables to prevent any chance of conflict.
Author by
Mauro Cruz
Updated on June 19, 2022Comments
-
Mauro Cruz almost 2 years
I have to insert many data in my application and through the graphical interface it takes many time. For this reason I want to create a bash script and make the requests through curl using the REST API (I have to manually specify the id).
The problem is that i get the error: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Here is the code
#!/bin/bash for i in {1..1} do CURL='/usr/bin/curl -X POST' RVMHTTP="http://192.168.1.101:8080/sitewhere/api/devices -H 'accept:application/json' -H 'content-type:application/json' -H 'x-sitewhere-tenant:sitewhere1234567890' --user admin:password" DATA=" -d '{\"hardwareId":\"$i",\"siteToken\":\"4e6913db-c8d3-4e45-9436-f0a99b502d3c\",\"specificationToken\":\"82043707-9e3d-441f-bdcc-33cf0f4f7260\"}'" # or you can redirect it into a file: $CURL $RVMHTTP $DATA >> /home/bluedragon/Desktop/tokens done
The format of my request has to be json