首页 > 解决方案 > 可选择在 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 警告,上述方法是否可以接受?

标签: bashshellcurlshellcheck

解决方案


您在变量周围加上引号是正确的,但shellcheck没有发现将命令存储在有其自身缺陷的变量中的问题。由于这是 shell 功能的一个问题,shellcheck因此无法立即使用它。当你在下面做

creds="-u ${user}:${password}"

和引用"$creds",它作为一个单独的参数字传递给curl而不是被分解为-u"${user}:${password}"单独的。正确的方法应该是使用一个数组来存储命令并扩展它,以便保留单词而不是被 shell 拆分(引用变量的首要原因,如 所示shellcheck

creds=(-u "${user}:${password}")

并调用

curl "${creds[@]}" <rest-of-the-cmd>

还探索以下

  1. 我正在尝试将命令放入变量中,但复杂的情况总是失败!
  2. 如何将命令存储在 shell 脚本的变量中?

推荐阅读