2016-04-24 113 views
0

在下面的bash腳本中,我循環了1-10,我想將索引傳入json字符串。不過,我想我錯誤地逃離美元符號,因爲JSON輸出是:Bash腳本轉義循環索引

tester\$i

,而不是

tester1 tester2

有沒有辦法做到這一點?

#!/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 

回答

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"}' 
+0

當我刪除「回聲」時,出現語法錯誤:curl:(3)[globbing]列18中的不匹配的大括號/括號 – Steve

+0

錯過了一個'\「'我更新了。 – SLePort