bash - 在 URL 中使用 Bash 变量会导致 "curl: (3) Illegal characters found in URL"

标签 bash curl

问题

我尝试在调用 cURL 命令时使用变量,但它包含文字 $line 而不是实际值。

while read line; do
  curl "https://x.com/v1/PhoneNumbers/$line?Type=carrier" -u "x:x" 
done < "${1:-/dev/stdin}"

上下文

我将一个数字列表传递给脚本,尝试逐行读取它们。

最佳答案

从评论中我们知道您收到以下错误:

curl: (3) Illegal characters found in URL

如果这样格式化:

while IFS="$IFS"$'\r' read line; do
  curl "https://x.com/v1/PhoneNumbers/$line?Type=carrier" -u "x:x" 
done < "${1:-/dev/stdin}"

你的命令应该可以工作。

问题在于您在输入行末尾附加了 \r (以便输入的每一行都以 \r\n 序列结尾)。默认情况下,read 不会删除尾随的r。如果我们想要 read 修剪这些字符,我们必须将此字符添加到 IFS 环境变量中进行 read,如下所示: IFS= “$IFS”$'\r')”读取...


这是来自 Charles Duffy 的精彩评论:

Personally, I'd suggest IFS=$' \t\n\r', not referring to the old $IFS value -- why make your code's behavior contextually dependent?

又一条宝贵意见;这次来自chepner :

Granted, a valid line probably isn't going to contain a \r, but conceptually, you don't want to treat a carriage return as whitespace; you just want to strip the \r that is part of the \r\n line ending. Instead of modifying IFS, read the line normally, then strip it with line=${line%$'\r'} before calling curl.


相关:

关于bash - 在 URL 中使用 Bash 变量会导致 "curl: (3) Illegal characters found in URL",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904431/

相关文章:

windows - gcc 可被 cmd 识别,但不能被 bash 识别

curl - js_of_ocaml : missing primitive when calling ocurl and str

bash - 如何从makefile规则导出变量?

linux - Bash 中的 MySQL 备份脚本

php - CURL PHP 握手失败 SSL

python - 将curl命令转换为Python pycurl或请求

当直接从浏览器调用 url 时,curl www.google.com 的工作方式有所不同

ssl - "SSL23_GET_SERVER_HELLO:reason(1112)"服务器端(Openshift)的解决方法?

linux - 在终端中运行的命令在 shell 脚本中不起作用

linux - 在 linux 中创建和终止某些终端