首页 > 解决方案 > 如何存储 for 循环结果并在命令中引用?

问题描述

我有一个如下所示的 for 循环,

values="addressSearchBaseUrl addressSearchSubscriptionKey cacheUrl calendarApiUrl checkoutBffApiUrl cpCode"

for ptr in $values
do
echo $ptr
temp=$(az pipelines variable-group list --group-name "${target_backend}"|jq '.[0].variables.'${ptr}'.value')
echo $temp
echo $?
done

现在,我希望在下面的命令中引用每个结果:

az pipelines variable-group variable create true  --name "Sales.Configuration.Spa ${new_env}" --variable "addressSearchBaseUrl" --value "${parse or store the value from above loop}" "addressSearchSubscriptionKey" "--value "${parse or store the value from above loop}"...

任何人都可以帮助我吗?

标签: arraysbashloops

解决方案


添加一些换行符确实有助于提高代码的可读性。

利用 shell 数组:

values=(
    addressSearchBaseUrl
    addressSearchSubscriptionKey
    cacheUrl
    calendarApiUrl
    checkoutBffApiUrl
    cpCode
)
az_create_options=()

for ptr in "${values[@]}"
do
    result=$(
        az pipelines variable-group list --group-name "${target_backend}" \
        | jq ".[0].variables.${ptr}.value"
    )
    printf "%s\t%s\t%d\n" "$ptr" "$result" $?

    # add the variable and value to the array
    az_create_options+=( --variable "$ptr" --value "$result" )
done

# inspect the create options, if you want
declare -p az_create_options

# now, create them
az pipelines variable-group variable create true  \
    --name "Sales.Configuration.Spa ${new_env}" \
    "${az_create_options[@]}"

推荐阅读