[英]How do I get a string from a curl response for a variable in bash?
The bash script sends a curl The curl response example is bash脚本发送curl卷曲响应示例是
{"code":"2aaea70fdccd7ad11e4ee8e82ec26162","nonce":1541355854942}
I need to get the random code "2aaea70fdccd7ad11e4ee8e82ec26162" (without quotes) and use it in the bash script. 我需要获取随机代码“ 2aaea70fdccd7ad11e4ee8e82ec26162”(不带引号)并在bash脚本中使用它。
Use jq
to extract the value from the JSON, and command substitution to capture the output of the command: 使用jq
从JSON中提取值,然后执行命令替换以捕获命令的输出:
code=$(curl ... | jq -r '.code')
The -r
( --raw
) prints the string directly instead of quoting it as in a JSON. -r
(-- --raw
)直接打印字符串,而不是像在JSON中那样引用它。
You can also achieve it by sed
command if you don't want to install jq: 如果不想安装jq,也可以通过sed
命令来实现:
json=`curl ...`
code=$(echo "$json" | sed -nE 's/.*"code":"([^\"]*)",".*/\1/p')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.