问题
我尝试在调用 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 modifyingIFS
, read the line normally, then strip it withline=${line%$'\r'}
before callingcurl
.
相关:
关于bash - 在 URL 中使用 Bash 变量会导致 "curl: (3) Illegal characters found in URL",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904431/