Bash中调用含多命令管道的变量执行curl时出现错误的问题求助
各位好,我现在碰到一个bash脚本的问题,想请教下大家怎么解决。
我正在写一个bash的for循环,用到的变量是从YAML文件里读取的。这个变量里不仅包含了curl要请求的URL,还跟着一整套管道命令——用jq解析返回数据、排序,最后提取出某个二进制文件的最新版本号。
我先输出了这个变量$version的内容:
echo $version
得到的结果是:
https://api.github.com/repos/hashicorp/vault/tags | jq -r '.[].name' | sort -Vr | head -n 1 | cut -c 2-)
如果我手动把整个命令串输进去执行,是完全正常的,能拿到正确的版本号:
curl -s https://api.github.com/repos/hashicorp/vault/tags | jq -r '.[].name' | sort -Vr | head -n 1 | cut -c 2-
执行结果:
1.14.2
但是当我用变量来调用curl的时候,就出问题了:
curl $version
直接弹出一堆错误提示:
Warning: Invalid character is found in given range. A specified range MUST
Warning: have only digits in 'start'-'stop'. The server's response to this
Warning: request is uncertain.
curl 8.2.1 (x86_64-alpine-linux-musl) libcurl/8.2.1 OpenSSL/3.0.10 zlib/1.2.13 brotli/1.0.9 nghttp2/1.51.0
Release-Date: 2023-07-26
Protocols: dict file ftp ftps gopher gophers http https imap imaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp ws wss
Features: alt-svc AsynchDNS brotli HSTS HTTP2 HTTPS-proxy IPv6 Largefile libz NTLM NTLM_WB SSL threadsafe TLS-SRP UnixSockets
我已经试过几种办法了:
- 给变量里的URL加转义双引号,再在变量首尾套一层双引号,没用;
- 把变量拆成两部分,
$version存curl的URL部分,$parse存后面的解析管道命令,结果又出现了新错误:curl: (23) Failure writing output to destination.
补充编辑:我还试过用"$version"的方式执行,结果报错:
curl: (3) URL rejected: Malformed input to a URL function.
我也试过在变量里的URL周围直接加双引号,同样不行。
备注:内容来源于stack exchange,提问作者Welo




