CURL逃脱单引号

时间:2015-08-20 15:40:34

标签: bash shell curl elasticsearch

我该如何做到这一点?

curl -XPOST 'http://localhost:9290/location/place' -d '{"geoloc": {"lat": "38.1899", "lon": "-76.5087"}, "longitude": "-76.5087", "admin_name1": "Maryland", "admin_name2": "St. Mary's", "admin_name3": "", "postal_code": "20692", "admin_code3": "", "country_code": "US", "admin_code1": "MD", "latitude": "38.1899", "admin_code2": "037", "accuracy": null, "place_name": "Valley Lee"}'

'中的Mary's导致此失败。我从像cat curl-cmd.txt | sh这样的文件运行它,但它也不能从命令行工作。我尝试过使用\'\\'以及\u0027(unicode '

我被困了

2 个答案:

答案 0 :(得分:45)

我遇到了同样的问题。最简单的解决方案是使用反斜杠转义撇号,并将其包装在一组单引号中。 '\''

对于您的使用案例,请将Mary's更改为Mary'\''s,它应该有效。

curl -XPOST 'http://localhost:9290/location/place' -d '{"geoloc": {"lat": "38.1899", "lon": "-76.5087"}, "longitude": "-76.5087", "admin_name1": "Maryland", "admin_name2": "St. Mary'\''s", "admin_name3": "", "postal_code": "20692", "admin_code3": "", "country_code": "US", "admin_code1": "MD", "latitude": "38.1899", "admin_code2": "037", "accuracy": null, "place_name": "Valley Lee"}'
  

另一种方法是将POST数据(-d)用双引号括起来,同时用反斜杠转义JSON字符串中所有嵌套的双引号出现。

curl -XPOST 'http://localhost:9290/location/place' -d "{\"geoloc\": {\"lat\": \"38.1899\", \"lon\": \"-76.5087\"}, \"longitude\": \"-76.5087\", \"admin_name1\": \"Maryland\", \"admin_name2\": \"St. Mary's\", \"admin_name3\": \"\", \"postal_code\": \"20692\", \"admin_code3\": \"\", \"country_code\": \"US\", \"admin_code1\": \"MD\", \"latitude\": \"38.1899\", \"admin_code2\": \"037\", \"accuracy\": null, \"place_name\": \"Valley Lee\"}"

答案 1 :(得分:3)

经验法则如果要在bash上的字符串中显式表示单引号或双引号, 使用反斜杠(\)取决于您的String Wrapper (应该是同一类型)。反斜杠(\)字符用于转义具有特殊含义的字符,例如换行符,反斜杠本身或引号字符。

示例

-双引号示例-Use \"

如果要使用bash She said "Yes I Do"

打印
echo "She said \"Yes I Do\""
#output:
She said "Yes I Do"

echo 'she said "Yes I Do"' 
#output:
She said "Yes I Do"

-单引号示例-Use '\''

如果要使用bash My Daughter's dog likes cat treats

打印
echo "My Daughter's dog likes cat treats"
#output:
My Daughter's dog likes cat treats

echo 'My Daughter'\''s dog likes cat treats' 
#output:
My Daughter's dog likes cat treats