bash - 可选择在 curl 请求中包含用户名和密码?
问题描述
我可以选择在 curl 请求中包含用户和密码,如下所示:
declare creds=""
if [ -n "$user" ] && [ -n "$password" ]; then
creds="-u ${user}:${password}"
fi
output=$(curl ${creds} -X PUT -v --write-out "%{http_code}" "$url" \
-H 'Content-Type: application/json' -s -o /dev/null --data "${payload}")
这似乎工作正常,但我收到了这个 shellcheck 警告:
Double quote to prevent globbing and word splitting
https://github.com/koalaman/shellcheck/wiki/SC2086
在它周围加上引号是行不通的,例如,如果我这样做:
output=$(curl "${creds}" -X PUT -v --write-out "%{http_code}" "$url" \
-H 'Content-Type: application/json' -s -o /dev/null --data "${payload}")
那么当没有提供用户名和密码时,这会导致 curl 请求中的双引号为空curl "" -X PUT ...
,从而产生<url> malformed
错误。
我可以为 curl 命令使用 if-else,但我宁愿避免重复。尽管有 shellcheck 警告,上述方法是否可以接受?
解决方案
您在变量周围加上引号是正确的,但shellcheck
没有发现将命令存储在有其自身缺陷的变量中的问题。由于这是 shell 功能的一个问题,shellcheck
因此无法立即使用它。当你在下面做
creds="-u ${user}:${password}"
和引用"$creds"
,它作为一个单独的参数字传递给curl
而不是被分解为-u
和"${user}:${password}"
单独的。正确的方法应该是使用一个数组来存储命令并扩展它,以便保留单词而不是被 shell 拆分(引用变量的首要原因,如 所示shellcheck
)
creds=(-u "${user}:${password}")
并调用
curl "${creds[@]}" <rest-of-the-cmd>
还探索以下
推荐阅读
- azure-virtual-machine - 我的 Azure 门户中突然停止了 100 个 Vm
- elf - ELF - sh_offset 字段的目的是什么?
- ios - 从 xmpp 服务器获取归档消息 - Swift
- yaml - Ansible/yaml:for 语法中的 if 语法
- spring-boot - 在 Spring Boot 中的 @Transactional 方法之后,实体未在 Exposed 中持久化
- javascript - 在 React Js 中禁用元素
- jquery - 将内联样式添加到可见的最后一个孩子
- sql-server - SQL Server 查询 if then 逻辑
- mathjax - 在 MathJax 等浏览器中使用 TikZ
- ios - 核心数据:从不同设备上的备份恢复