【问题标题】:Bad/illegal format or missing URL - Passing variable value inside custom curl [duplicate]错误/非法格式或缺少 URL - 在自定义 curl 中传递变量值 [重复]
【发布时间】:2021-05-19 07:08:53
【问题描述】:

我在我的 Windows 10 机器中使用 Linux shell (Ubuntu 20.04)。我有一个 bash 脚本应该是

  1. 浏览包含 IP 列表的 .txt 文件
  2. 使用站点 https://ipinfo.io/ 对每个 IP 进行卷曲,以获得修改后的卷曲输出
#!/bin/bash  
input="/mnt/d/Docs/BR Resources/iplist.txt"  
while IFS= read -r line  
do   
 curl https://ipinfo.io/$line  
done < "$input"

循环中每个 IP 的预期输出是:

{ "ip": "xx.xx.xx.xx",
"主机名": "c0241.brsol.com",
“城市”:“阿什本”,
“地区”:“弗吉尼亚”,
“国家”:“美国”,
"loc": "xx.xxxx,xx.xxxx", "org": "BR, Inc.",
“邮政”:“xxxxx”,
"时区": "美国/纽约",
“自述文件”:“https://ipinfo.io/missingauth”}

但是,我得到的输出是这个错误:

curl:(3) URL 使用错误/非法格式或缺少 URL

iplist.txt 的示例摘录

36.13.6.167
252.125.137.71
204.50.68.40
136.122.209.112
203.47.25.30
223.96.93.56
64.137.82.169
11.183.223.40
199.169.87.25
119.198.39.119

问题似乎是 $line 的值没有与 curl 命令的其余部分一起传递

如何解决此问题以获取此 .txt 文件中每个 IP 的修改后的 Curl 输出?

【问题讨论】:

  • 你能提供一个iplist.txt的例子吗?
  • 先用 echo 运行这个循环:while IFS= read -r line; do echo "https://ipinfo.io/$line"; done &lt; "$input"
  • 脚本或 iplist.txt 文件是否为 DOS/Windows 格式(参见 this question)?如果这不是问题,请尝试将set -x 放在脚本的开头,它会在运行时打印正在发生的事情,这有助于找出问题所在。
  • 将 shebang 更改为 #! /bin/bash -x 以查看有关正在执行的命令的更多详细信息。这很可能是 Windows 问题 :-)
  • @Sandun \r 表示 URL 末尾有一个(通常不可见的)回车符,可能是因为 ipinfo.txt 文件是 DOS/Windows 格式。如果您有dos2unix 命令,它会将文件转换为unix 格式。您也可以使用while IFS=$'\r' read ... 获取read 为您去除回车。 question I linked earlier 有更多详细信息和选项。

标签: bash ubuntu curl ip windows-subsystem-for-linux


【解决方案1】:

我在生成输出的 Windows 机器上执行了以下步骤:
将文件转换为dos2unix.exe ./test.sh

test.sh:

# !/usr/bin/bash
input="iplist.txt"  
while IFS= read -r line  
do   
 curl https://ipinfo.io/$line  
done < "$input"

收到的输出:

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   300  100   300    0     0    300      0  0:00:01 --:--:--  0:00:01   532
{
  "ip": "36.13.6.167",
  "hostname": "kd036013006167.ppp-bb.dion.ne.jp",
  "city": "Saitama",
  "region": "Saitama",
  "country": "JP",
  "loc": "35.9081,139.6566",
  "org": "AS2516 KDDI CORPORATION",
  "postal": "330-0853",
  "timezone": "Asia/Tokyo",
  "readme": "https://ipinfo.io/missingauth"
}  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

bash 版本:GNU bash,版本 4.3.42(4)-release

【讨论】:

  • 您好,您能详细说明一下第二行吗?将文件转换为 dos2unix.exe ./test.sh ?这是否意味着我必须在我的 Ubuntu Shell(在 Windows 机器内)中安装一个名为 dos2unix 的东西?
  • @Sundun 我看到你的 shell 脚本是 DOS 格式(\r / 回车 CRLF)而不是 unix 格式。可能是你使用了像 notepad++ 这样的编辑器,它把文件做成了 dos 格式,所以我通过dos2unix操作将它转换为unix文件。然后,该文件将在 unix 上正常工作。Dos 格式为:CRLF(每行以 CR 结尾,然后 LF),Unix 格式为:仅 LF(每行以 LF 字符结尾)。您可以使用以下命令在 ubuntu 中安装它:sudo apt-get install dos2unix
猜你喜欢
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 2022-10-14
相关资源
最近更新 更多