【问题标题】:Bash script escape for loop index循环索引的 Bash 脚本转义
【发布时间】:2016-08-17 12:58:32
【问题描述】:

在下面的 bash 脚本中,我正在循环 1-10,我想将索引传递到 json 字符串中。但是,我认为我错误地转义了美元符号,因为 json 输出是:

测试者\$i

而不是

测试仪1 测试仪2

有没有办法做到这一点?

#!/bin/bash
for i in `seq 1 10`;
do
    curl -X POST http://localhost:9000/api/resources --header Content-Type:application/json --data '{"name":"tester\\$i", "text":"some text"}'
done   

【问题讨论】:

    标签: bash loops curl escaping


    【解决方案1】:

    $i 必须用双引号括起来以允许扩展变量,并且必须转义内部 json 双引号:

    for i in `seq 1 10`;
    do
         curl -X POST http://localhost:9000/api/resources --header Content-Type:application/json --data "{\"name\":"tester$i\", \"text\":\"some text\"}"
    done 
    

    另一种(更简单)的方法是引用变量:

    curl -X POST http://localhost:9000/api/resources --header Content-Type:application/json --data '{"name":"tester'$i'", "text":"some text"}'
    

    【讨论】:

    • 删除“echo”时,出现语法错误:curl: (3) [globbing] 第 18 列中的右大括号/括号不匹配
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2016-08-16
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多