bash脚本看起来正确,但给出“JSON意外结束”/“curl错误(3):输入多个单词时出现不匹配的右大括号”

jei2mxaa  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(159)

我希望我的bash脚本接受一些输入并在cURL POST的主体中使用它。

function testBashImport() {
    clientPath="/Users/sunny/Desktop/Projects/myDir"
    cd $clientPath/app/package
    filePath=`readlink -f *.zip`
    echo "Please add a release note:"
    read releaseNote
    while [ "$releaseNote" = "" ]
    do echo ""
    echo "IT IS REQUIRED TO ADD A RELEASE NOTE!!!"
    echo "Please add a release note:"
    read releaseNote
    done

    echo "Please wait..."
    curl -X --location --request POST 'http://localhost:3030/file-manager/uploadFile' \
--header 'Authorization: Basic someAuthKey==' \
--header 'Cookie: connect.sid=s%some.header%key%here' \
--form 'fileData=@"'$filePath'"' \
--form 'data="{\"releaseNotes\": \"'$releaseNote'\"}"'

    echo ""
}
export -f testBashImport

当releaseNote是一个单词(如hello或lskdjf)时,脚本似乎可以工作

MAC-K03NF:package user$ testBashImport
Please add a release note:
hello
Please wait...
{"status":"success"}

但当我使用相同的脚本并使releaseNote包含多个单词时,即hello world或kdsfl sldfk sd,它会失败,并出现一些错误:

MAC-K03NF:package user$ testBashImport
Please add a release note:
hello hi hey world
Please wait...
Unexpected end of JSON input
curl: (6) Could not resolve host: hi
curl: (6) Could not resolve host: hey
curl: (3) unmatched close brace/bracket in URL position 8:
world\"}"

备注:

  • 当我使用postman时,API端点可以正常工作
  • 我已经隐藏了基本的身份验证内容
  • 我必须使用--form因为我必须将文件作为正文的一部分发送
    任何帮助都是感激不尽的。谢谢!
uwopmtnx

uwopmtnx1#

可能是引用问题。
请看下面这一行,并添加一些注解来帮助分析引用状态:

#      open quote                  close quote  open  close
#      |                           |            |     | 
#      V                           V            V     V
--form 'data="{\"releaseNotes\": \"'$releaseNote'\"}"'

因为releaseNote根本没有加引号,所以如果它里面有空格,那么当Bash解析命令时就会触发Word Splitting。
data="{\"releaseNotes\": \"hello hi hey world\"}"
Bash在这个空格上进行了拆分,并创建了 * 四个 * 参数:data="{\"releaseNotes\": \"hellohiheyworld\"}"。但这对这个命令不起作用。
所以简单地说:在此处用双引号将$releaseNote括起来。
--form 'data="{\"releaseNotes\": \"'"$releaseNote"'\"}"'

相关问题