在bash脚本中引用空间

问题描述

我有一个脚本,需要传递包含空格的字符串。

基本上,我想收集调用curl "https://my-api.com" -H'X-API-Key: API key here'

错误返回

以下方法有效,但我确实希望避免使用eval。我敢肯定有一种更简洁的编写方式,但是找不到。

    CURL="curl -s --fail $URL -H\"X-API-Key:$API_KEY\""
    return $(eval "$CURL" >> /dev/null)

解决方法

这是Dynamically building a command in bash的副本,但这是您的代码的修补程序。

请花点时间阅读上级问题的答案。

# Build the curl command with its arguments in an array
curl_cmd=(curl -s --fail "$URL" -H "X-API-Key:$API_KEY")

# Execute the curl command with its arguments from the curl_cmd array
"${curl_cmd[@]}"