如何通过 shell 命令行传入参数变量到 curl 请求字符串中 All In One
如何通过 shell 命令行传入参数变量到 curl 请求字符串中 All In One
curl 接收 shell
变量$1,同时给变量设置一个缺省值/默认值

solutions
- 手动转义
# 如果没有传入参数,则使用默认值 "Eric"
NAME="${1:-Eric}"
# NAME="$1"
# NAME="Eric"
curl -X POST -i http://localhost:3000/profiles \
-H "Content-Type: application/json" \
-d "{
\"name\": \"$NAME\",
\"desc\": \"This JavaScript coder is a master of syntax, a weaver of the web, and a connoisseur of coffee.\"
}"
- jq 自动转义
NAME="${1:-Eric}"
DESC="${2:-hello world}"
# jq 是一个处理 JSON 的命令行工具
# 读取 JSON
# 生成 JSON
# 过滤 JSON
# 把变量转成 JSON 字符串
jq -n --arg name "$NAME" --arg desc "$DESC" \
'{name: $name, desc: $desc}' | \
curl -X POST "http://localhost:3000/profiles" \
-H "Content-Type: application/json" \
--data @-
demos
详细解释一下,使用 jq 更安全的写法,各个符号是什么意思
NAME="${1:-Eric}"
DESC="${2:-hello world}"
jq -n --arg name "$NAME" --arg desc "$DESC" \
'{name: $name, desc: $desc}' | \
curl -X POST "http://localhost:3000/profiles" \
-H "Content-Type: application/json" \
--data @-
更安全的写法, 想避免转义问题,推荐使用 jq
-n 表示,不从标准输入读取 JSON,而是直接构造一个新的 JSON 对象
--arg name "$NAME",定义一个 jq 变量 名字叫 name 值来自 shell 变量 \(NAME
--arg = “传一个字符串参数”
name = jq 里的变量名
"\)NAME" = shell 变量的值
{name: $name, desc: $desc} jq 的对象构造语法
创建一个 JSON 对象,里面有两个字段
name 的值来自 jq 变量 $name, desc 的值来自 jq 变量 $desc
| 管道符号, 把前一个命令的输出,作为下一个命令的输入
jq 先生成 JSON, 然后把 JSON 输出传给 curl,curl 再把它当作请求体发送
curl -X POST ... --data @-
@- 很关键 ✅
@- 表示“从标准输入读取数据”
因为前面 jq 的输出通过管道送到了这里
所以 curl 会把它当作请求体发送
它避免了手写 JSON 时的常见问题:
- 变量里有引号
- 变量里有换行
- 变量里有特殊字符
- 转义符搞乱了 JSON
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
jq
jq is a
lightweightandflexiblecommand-lineJSONprocessor.
jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
jq is written in portable C, and it has zero runtime dependencies. You can download a single binary, scp it to a far away machine of the same type, and expect it to work.
jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you'd expect.
https://www.cnblogs.com/xgqfrms/p/19784842
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/23049769
未经授权禁止转载,违者必究!

浙公网安备 33010602011771号