2013-10-11 31 views
1

我現在使用bash shell腳本測試一些restful API。 我想從文件中讀取url,然後用文件中的url創建一個json數據字符串。 對於測試,下面的代碼工作正常。它不是從文件中讀取的。使用字符串中的url字符串時發生curl錯誤

#!/bin/bash 
URL=http://test.com/test.jpg 
curl -X POST \ 
-H "Content-Type:application/json" \ 
-H "accept:application/json" \ 
--data '{"url":"'"$URL"'"}' \ 
http://api.test.com/test 

但是,它會返回一些錯誤,當我使用下面的代碼。

#!/bin/bash 
FILE=./url.txt 
cat $FILE | while read line; do 
echo $line # or whaterver you want to do with the $line variable 
curl -X POST \ 
-H "Content-Type:application/json" \ 
-H "accept:application/json" \ 
--data '{"url":"'"$line"'"}' \ 
http://api.test.com/test 
done 

但是,當我從閱讀文件中使用字符串時,它會返回錯誤。 這是錯誤消息。

非法無引號字符((CTRL-CHAR,代碼13)):必須使用反斜槓轉義在[來源將被包括在字符串值 :[email protected] ;行:1,列:237]

如何解決此問題? 當我從文件讀取中使用字符串時爲什麼會返回錯誤?

回答

0

看起來你的文件是DOS格式的,帶有\n\r行結束符。嘗試運行dos2unix以去除\r。此外,沒有必要cat文件,使用重定向,像這樣

while read -r line; do 
echo $line # or whaterver you want to do with the $line variable 
curl -X POST \ 
-H "Content-Type:application/json" \ 
-H "accept:application/json" \ 
--data '{"url":"'"$line"'"}' \ 
http://api.test.com/test 
done < "$FILE" 

此外,通路-rread防止反斜槓

+0

感謝快速回復,但它返回相同的錯誤。 T_T – user2869281

+0

@ user2869281,只要確定,在嘗試之前是否在文件上運行了'dos2unix'? – iruvar

+0

太好了!你是天才!謝謝,它解決了! – user2869281

相關問題