bash - curl 命令负载中字符串的脚本连接

标签 bash shell curl string-concatenation

我使用 curl 来测试用户帐户创建 API,如下所示:

curl -s -X POST "https://$APISERVER/users" \
-H 'Content-Type: application/json' \
-d '{ \
"username": "'$NEWUSERNAME'", \
"firstName": "'$NEWUSERFIRSTNAME'", \
"lastName": "'$NEWUSERLASTNAME'", \
"displayName": "'$NEWUSERDISPLAYNAME'", \
"password": "'$NEWUSERPASSWORD'" \
}'

并且变量是通过命令行参数提供的:

APISERVER=http://localhost:8080
NEWUSERNAME=$1
NEWUSERPASSWORD=$2
NEWUSERFIRSTNAME=$3
NEWUSERLASTNAME=$4

# Calculated variable
NEWUSERDISPLAYNAME="${NEWUSERFIRSTNAME} ${NEWUSERLASTNAME}"

脚本调用示例如下:./test-new-user.sh jdoe Hello123 John Doe,产生以下变量值:

NEWUSERNAME=jdoe
NEWUSERPASSWORD=Hello123
NEWUSERFIRSTNAME=John
NEWUSERLASTNAME=Doe

(我打算将 NEWUSERDISPLAYNAME 设置为“John Doe”)

但我从服务器返回了一个异常,因为 curl 命令中的有效负载似乎被截断、不完整或格式错误。

JSON parse error: Unexpected end-of-input in VALUE_STRING\n at [Source: 
java.io.PushbackInputStream@2eda6052; line: 1, column: 293]; nested 
exception is com.fasterxml.jackson.databind.JsonMappingException: 
Unexpected end-of-input in VALUE_STRING\n at [Source: 
java.io.PushbackInputStream@2eda6052; line: 1, column: 293]\n at 
[Source: java.io.PushbackInputStream@2eda6052; line: 1, column: 142] 
(through reference chain: 
com.mycompany.api.pojos.NewUser[\"displayName\"])"

如果我在上面的 curl 命令中硬编码 displayName 的值(如下所示),用户创建请求将通过并完美运行。

"displayName": "John Doe", \

我怀疑这与 displayName 中的空格以及我如何使用 "'$NEWUSERDISPLAYNAME'" 插入 displayName 的值有关.在 curl 命令的 POST 请求负载中执行变量替换是否有安全的方法?

最佳答案

您需要引用 shell 变量:

curl -s -X POST "https://$APISERVER/users" \
-H 'Content-Type: application/json' \
-d '{ \
"username": "'"$NEWUSERNAME"'", \
"firstName": "'"$NEWUSERFIRSTNAME"'", \
"lastName": "'"$NEWUSERLASTNAME"'", \
"displayName": "'"$NEWUSERDISPLAYNAME"'", \
"password": "'"$NEWUSERPASSWORD"'" \
}'

为了避免过多引用,试试这个 printf:

printf -v json -- '{ "username": "%s", "firstName": "%s", "lastName": "%s", "displayName": "%s", "password": "%s" }' \
"$NEWUSERNAME" "$NEWUSERFIRSTNAME" "$NEWUSERLASTNAME" "$NEWUSERDISPLAYNAME" "$NEWUSERPASSWORD"

curl -s -X POST "https://$APISERVER/users" \
    -H 'Content-Type: application/json' \
    -d "$json"

关于bash - curl 命令负载中字符串的脚本连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50613030/

相关文章:

linux - UNIX shell 脚本在作为计划任务运行时失败

python - 有没有办法获取目录中 N 个最旧的文件名而不获取所有文件名(在 python 或 shell 中首选)

PHP curl 如何在使用代理时检索 header 。 CURLOPT_HEADERFUNCTION?

bash - 以特定方式读取脚本的输出

bash - while循环后的左尖括号在bash中意味着什么?

xml - 编写 : How to use XMLStarlet to extract values in pom. xml 文件的脚本

php - 使用 Shopify API 在 PHP 中创建产品

bash - 命令建议在 bash shell 中是如何实现的?

linux - 在脚本中启用作业控制时,为什么无法捕获进程信号?

php - Watson 概念扩展服务