带有 for 循环和“数组”的 Shell 脚本

带有 for 循环和“数组”的 Shell 脚本

如何将此 shell 脚本与 for 循环和数组一起使用。我想使用 for 循环调用创建 sonarqube 质量门的创建条件。例子:

#!/bin/bash --login

echo "Creating SonarQube Gateway Condition"

QG_ID=$(cat qualitygate.json | jq -r ".id")
Gateway="curl -u ${USERNAME}:${PASSWORD} -k -X POST "${SONAR_HOST_URL}/api/qualitygates/create_condition?"
declare -a gateMetrics=("gateId=$QG_ID&metric=coverage&op=LT&error=80\"" "gateId=$QG_ID&metric=duplicated_lines_density&op=GT&error=10\"")

for val in "${gateMetrics[@]}"
do
  echo $Gateway$val
done

运行上面的命令后我想要如下的输出

curl -u ${USERNAME}:${PASSWORD} -k -X POST "${SONAR_HOST_URL}/api/qualitygates/create_condition?gateId=$QG_ID&metric=coverage&op=LT&error=80"

答案1

你可以把它分解成更小的部分。

#!/bin/bash --login

echo "Creating SonarQube Gateway Condition"

curl_cmd=( curl -u "${USERNAME}:${PASSWORD}" -k -X POST )
url="${SONAR_HOST_URL}/api/qualitygates/create_condition"
qg_id=$( jq -r ".id" qualitygate.json )
gateMetrics=(
    coverage,LT,80
    duplicated_lines_density,GT,10
)
query_fmt="gateId=%s&metric=%s&op=%s&error=%s"

for metric in "${gateMetrics[@]}"; do
    IFS=, read -r m o e <<< "$metric"
    printf -v query "$query_fmt" "$qg_id" "$m" "$o" "$e"

    # remove this echo if it looks OK
    echo "${curl_cmd[@]}" "${url}?${query}"
done

您还想阅读我试图将命令放入变量中,但复杂的情况总是失败!

答案2

用户名变量;为自运行示例添加了 PASSWORD 和 QG_ID:

#!/bin/bash --login

USERNAME=foo
PASSWORD=bar
SONAR_HOST_URL="https://sonar.example.com"

echo "Creating SonarQube Gateway Condition"

# QG_ID=$(cat qualitygate.json | jq -r ".id")
QG_ID=123456

Gateway="curl -u ${USERNAME}:${PASSWORD} -k -X POST \"${SONAR_HOST_URL}/api/qualitygates/create_condition?"
declare -a gateMetrics=("gateId=$QG_ID&metric=coverage&op=LT&error=80\"" "gateId=$QG_ID&metric=duplicated_lines_density&op=GT&error=10\"")

for val in "${gateMetrics[@]}"; do
  echo "$Gateway$val"
done

输出:

Creating SonarQube Gateway Condition
curl -u foo:bar -k -X POST "https://sonar.example.com/api/qualitygates/create_condition?gateId=123456&metric=coverage&op=LT&error=80"
curl -u foo:bar -k -X POST "https://sonar.example.com/api/qualitygates/create_condition?gateId=123456&metric=duplicated_lines_density&op=GT&error=10"

相关内容