1

我现在正在使用 bash shell 脚本测试一些宁静的 API。我想从文件中读取 url,然后用文件中的 url 创建一个 json 数据字符串。对于测试,以下代码可以正常工作。它不是从文件中读取的。

#!/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)):必须使用反斜杠转义才能包含在 [Source: org.apache.catalina.connector.CoyoteInputStream@27eb679c; 行:1,列:237]

如何解决这个问题?为什么当我使用文件读取中的字符串时会返回错误?

4

1 回答 1

0

您的文件似乎是带有\n\r行终止符的 dos 格式。尝试在其上运行dos2unix以剥离\rs。另外,不需要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"

另外,传递-r给以read防止反斜杠转义

于 2013-10-11T01:45:33.823 回答