I have a problem when using curl on my linux script:
#!/bin/bash userName="user"; passWord="password"; tenantName="tenant"; commande="curl -X POST -H \"Content-Type: application/json\" -H \"Cache-Control: no-cache\" -H \"Postman-Token: 111131da-8254-21b3-1b95-9c12954152c9\" -d '{\"auth\":{\"tenantName\":\"$tenantName\",\"passwordCredentials\": {\"username\":\"$userName\",\"password\":\"$passWord\"}}}' \"http://controller:5000/v2.0/tokens\""
When the output of the variable commande is copy pasted into the shell it works, but when i use :
res= $(eval $commande) #or res=`$commande`
Neither one of those commands works, and this is the output error i usually get:
line 11: {"access":: command not found
PS: If i do
echo $commande
And then i copy past the result on the shell it works,If anyone can help me that would be great !
1 Answer 1
A variable is for data, not code. Define a function. This also simplifies your quoting.
#!/bin/bash
userName="user"
passWord="password"
tenantName="tenant"
commande () {
curl -X POST \
-H "Content-Type: application/json" \
-H "Cache-Control: no-cache" \
-H "Postman-Token: ..." \
-d@- \
http://controller:5000/v2.0/tokens <<EOF
{
"auth": {
"tenantName": "$tenantName",
"passwordCredentials": {
"username": "$userName",
"password": "$password"
}
}
}
EOF
}
The above also reads the JSON from a here-document (@-
reads the argument for the -d
option from standard input) instead of embedding it in a string to further simplify quoting.
However, it is also a bad idea to hand-code JSON like this if you aren't ensuring that the values of userName
, passWord
, and tennatnName
are properly JSON-encoded. A better solution is to use something like jq
to generate proper JSON for you.
commande () {
json_template='{
auth: {
tenantName: $tn,
passwordCredentials: {
username: $un,
password: $pw
}
}
}'
jq -n --arg un "$userName" \
--arg pw "$passWord" \
--arg tn "$tenantName" "$json_template" |
curl -X POST
-H "Content-Type: application/json" \
-H "Cache-Control: no-cache" \
-H "Postman-Token: ..." \
-d@- \
http://controller:5000/v2.0/tokens
}
-
Does the function commande returns the output of the curl command as i wanted ?Kingofkech– Kingofkech2017年03月13日 14:11:59 +00:00Commented Mar 13, 2017 at 14:11
commande
in one place, andcomande
in another. Also{"access":
looks like part of a JSON snippet, but your first code snippet doesn't have that anywhere.res=`$commande`
instruction? That attempt is less wrong than the other one.