Bash脚本中curl调用container参数报错,求排查方案
问题排查与解决
核心问题
你的脚本存在两个关键错误:
- 单引号导致变量无法解析:Bash中,单引号包裹的内容会被当作纯字符串处理,不会解析变量或命令替换。你把整个URL放在单引号里,
$(container)会被直接当作URL路径的一部分发送给服务器,而非替换成你定义的container变量值,这会导致请求路径错误。 - 变量引用语法错误:
$(container)是命令替换语法,会尝试执行名为container的命令并获取其输出。如果你想引用container变量,正确写法是$container。
修复后的脚本
将URL改为双引号包裹(Bash会解析双引号内的变量),同时修正变量引用:
curl -X GET "https://mycontainer/api/v2.0/projects/testproject/repositories/$container/artifacts?page=1&page_size=1&with_tag=true&with_label=false&with_scan_overview=false&with_signature=false&with_immutable_status=false&with_accessory=false" -H 'accept: application/json' -H 'X-Accept-Vulnerabilities: application/vnd.security.vulnerability.report; version=1.1, application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0' -H 'authorization: Basic YWhtZXQuY2Fua2F5YUBucy5ubDo2MkVEbDIxUEM=' | jq '.[].tags[].name' > output2.txt
更清晰的写法
如果担心URL中的特殊字符产生干扰,可以拆分静态部分与变量部分拼接,提升可读性:
# 假设你已定义container变量 container="your-target-container" # 拼接URL:静态部分用单引号,变量部分直接拼接 api_url='https://mycontainer/api/v2.0/projects/testproject/repositories/'$container'/artifacts?page=1&page_size=1&with_tag=true&with_label=false&with_scan_overview=false&with_signature=false&with_immutable_status=false&with_accessory=false' curl -X GET "$api_url" \ -H 'accept: application/json' \ -H 'X-Accept-Vulnerabilities: application/vnd.security.vulnerability.report; version=1.1, application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0' \ -H 'authorization: Basic YWhtZXQuY2Fua2F5YUBucy5ubDo2MkVEbDIxUEM=' \ | jq '.[].tags[].name' > output2.txt
内容的提问来源于stack exchange,提问作者Ukchat
相关产品推荐
相关产品推荐

