【问题标题】:curl error when using url string from string使用字符串中的 url 字符串时出现 curl 错误
【发布时间】:2013-10-11 01:39:13
【问题描述】:

我现在正在使用 bash shell 脚本测试一些 RESTful 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)):必须使用反斜杠转义才能包含在字符串值中 在 [来源:org.apache.catalina.connector.CoyoteInputStream@27eb679c;行:1,列:237]

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

【问题讨论】:

    标签: json bash shell curl


    【解决方案1】:

    您的文件似乎是带有\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 以防止反斜杠转义

    【讨论】:

    • @user2869281,请确认一下,您在尝试之前是否在文件上运行了dos2unix
    猜你喜欢
    • 2020-11-27
    • 2019-06-02
    • 1970-01-01
    • 2015-10-19
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多