我面临一个有趣的挑战,如何在 bash 脚本中转义引号。
我的 bash 脚本有一个很长的 curl 调用,并传递了一个大的 -d json 结构。
#!/bin/bash
Value4Variable=Value4
curl -s -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d \
'{"Variable1":"Value1",
"Variable2":"Value2\'s", # escape of quote doesnt work because of the previous single quote and backslash
"Variable3":"Value3",
"Variable4":"'"$Value4Variable"'",
"Variable5":"Value5"
}' \
https://www.hashemian.com/tools/form-post-tester.php
在 json 结构中添加单引号的最佳方法是什么?我尝试过各种组合但没有成功。
答案1
有多种方法可以使用不同的引号转义长字符串。最简单的是结束单引号并转义单引号:
'...'\''...'
但您可以做一些更好的事情。 Heredocs 是避免引用问题的好方法:
curl -s -X POST https://www.hashemian.com/tools/form-post-tester.php \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d @- <<EOF
{
"Variable1":"Value1",
"Variable2":"Value2's",
"Variable3":"Value3",
"Variable4":"$Value4Variable",
"Variable5":"Value5"
}
EOF
@-
告诉curl从stdin读取并<<EOF
启动heredoc,它将被输入到curl的stdin中。 Heredoc 的好处是,您不需要转义任何引号,并且可以在其中使用 bash 变量,从而避免了担心如何转义引号的需要,并使整个事情更具可读性。
答案2
我将使用--data @filename
符号从文件中读取数据:
样本json-data-file
内容:
{"Variable1":"Value1",
"Variable2":"Value2's",
"Variable3":"Value3",
"Variable4":"'$Value4Variable'",
"Variable5":"Value5"
}
请求:
Value4Variable="Value4"
curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" \
-d @<(sed "s/\$Value4Variable/$Value4Variable/" json-data-file) \
https://www.hashemian.com/tools/form-post-tester.php/test123
输出:
The POSTed value is:
********************
{"Variable1":"Value1", "Variable2":"Value2's","Variable3":"Value3","Variable4":"'Value4'", "Variable5":"Value5"}
********************
Results saved to: test123
*Note: Results are purged periodically. 1 hr minimum life.
答案3
考虑使用 JSON 感知工具来创建 JSON 文档。这样做将消除手动转义特殊字符(如制表符、换行符、双引号等)的需要。单引号实际上是一个字符不需要在 JSON 中转义。您只需要确保 shell 使用正确的引号即可正确识别您的字符串。
工具jo
从这里旨在使从命令行创建 JSON 文档变得非常简单:
somevariable2='line1
line2
line3'
curl -s -X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d "$( jo \
variable1="Value1" \
variable2="$somevariable2" \
variable3='String with "quotes"' \
variable4="It's raining!" \
variable5='\/\/\/\/\/' )" \
'https://www.hashemian.com/tools/form-post-tester.php'
或者
somevariable2='line1
line2
line3'
jo \
variable1="Value1" \
variable2="$somevariable2" \
variable3='String with "quotes"' \
variable4="It's raining!" \
variable5='\/\/\/\/\/' |
curl -s -X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d @- \
'https://www.hashemian.com/tools/form-post-tester.php'
任意一段代码的响应是
The POSTed value is:
********************
{"variable1":"Value1","variable2":"line1\nline2\nline3","variable3":"String with \"quotes\"","variable4":"It's raining!","variable5":"/\\/\\/\\/\\/"}
********************