将单引号添加到bash中一行的变量

时间:2018-11-28 10:19:03

标签: unix

我有一个函数get_info_using_api,它可以再调用一个函数get_data 函数get_data带有一些参数并执行curl命令 这是内容

function get_data() {
    local http_method="${1}"
    local rest_call_url="${2}"
    local other_paramas="${3}"
    curl -s -k "${other_paramas}" -X $http_method $rest_call_url
}

现在我的get_info_using_api看起来像这样

function get_info_using_api {
    local api_key=${1}
    local other_curl_options="-H "'Content-Type:application/json'" -H "'X-user:'$api_key''""
    local http_method=GET
    local url=something
    data=$(get_curl_data $http_method $jenkins_url "${other_curl_options}")
}

因此,当我调用此函数get_info_using_api时,执行的curl命令是 curl -s -k '-H Content-Type:application/json -H user:api_key' -X GET url

而我需要的是 curl -s -k '-H Content-Type:application/json' -H 'user:api_key' -X GET url

我正在尝试在行中添加这些单引号,但我无法这样做。 有人可以帮我吗

1 个答案:

答案 0 :(得分:0)

将它们放入数组中。

function get_info_using_api {
    local api_key="${1}"
    local other_curl_options=(
        "-H 'Content-Type:application/json'"
        "-H 'X-user:$api_key'"
    )
    local http_method=GET
    local url=something
    data=$(get_curl_data $http_method $jenkins_url "${other_curl_options[@]}")
}

您可以将单打字面意义上嵌入双打内,当您使用"${x[@]}"语法引用数组时,它将以单独的字符串返回args。

您可以使用以下方法测试逻辑:

$: x=( 1 2 3 )
$: printf "%s\n" "${x[@]}"
1
2
3

每个都单独打印。

相关问题