有两个独特的字段,所以我每次构建POST方法时都会编写一个生成随机值的命令,并将这些值存储到变量中并在CURL命令行中传递这些变量。脚本如下。
rcontactno=$(cat /dev/urandom | tr -dc '0-9' | fold -w 10 | head -n 1)
rfirstname=$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 10 | head -n
echo $rcontactno and $rfirstname
STATUS=$(curl -v -X POST -d '{"userName":"$rfirstname","contactNo":$rcontactno}' $1/restaurants/53/managers --header "Content-Type:application/json" --header "Accept:application/json" | grep HTTP | cut -d ' ' -f2 )
#Passing the URL using command-line argument
if [[ STATUS -eq 201 ]]; then
echo “Success”
exit 0
else
echo “Failed”
exit 127
fi
然后我按
执行脚本bash manager-post.sh
我遇到了这种类型的错误
> POST /restaurants/53/managers HTTP/1.1
> User-Agent: curl/7.37.1
> Host: my-url
> Content-Type:application/json
> Accept:application/json
> Content-Length: 54
>
} [data not shown]
* upload completely sent off: 54 out of 54 bytes
< HTTP/1.1 400 Bad Request
* Server Apache-Coyote/1.1 is not blacklisted
< Server: Apache-Coyote/1.1
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Fri, 16 Jan 2015 08:59:01 GMT
< Connection: close
<
{ [data not shown]
* Closing connection 0
“Failed”
但是当我在没有bash脚本的情况下运行curl命令并明确提到userName和contactNo的值时,它将成功执行。
我在哪里弄错了?
答案 0 :(得分:1)
单引号不允许shell中的变量扩展,因此您需要使用双引号。然后,您需要随后转义要按原样发送的双引号。
一种有用的调试技术是将--trace-ascii dump.txt
添加到命令行,并在调用curl后检查dump.txt,看它是否与您要发送的内容相匹配。