将字符串与 bash 中的字符串列表进行比较

Compare String with list of strings in bash

我正在尝试将服务与可用服务名称列表进行比较,如果在列表中找到服务,则更新服务,否则部署服务。 但在以下情况下,即使服务在列表变量中可用,也只部署新服务?

SERVNAME=ner
SERVICE=$(az ml service list -g $(ml_rg) --workspace-name $(ml_ws) --model-name $(model_name) --query "[].name")

if [[ "$SERVNAME" == "$SERVICE" ]];
then
   echo "Service Found: $(SERVNAME) and updating the service"
   az ml service update --name $(AKS_DEPLOYMENT_NAME) \
          --model '$(MODEL_NAME):$(MODEL_VERSION)' \
          --dc aksDeploymentConfig.json \
          --ic inferenceConfig.json \
          -e $(ml_env_name) --ev $(ml_env_version) \
          -g $(ml_rg) --workspace-name $(ml_ws) -v ;
else
   echo "Service Not found and starting deploying new service"
   az ml model deploy --name $(AKS_DEPLOYMENT_NAME) --model \
   '$(MODEL_NAME):$(MODEL_VERSION)' \
          --compute-target $(ml_aks_name) \
          --ic inferenceConfig.json \
          -e $(ml_env_name) --ev $(ml_env_version) \
          --dc aksDeploymentConfig.json \
          -g $(ml_rg) --workspace-name $(ml_ws) \
          --overwrite -v ;
fi

示例列表

SERVNAME="ner"
SERVICE=[ "ner", "aks-gpu-ner-0306210907", "aks-gpu-ner-30012231", "aks-gpu-ner-1305211336"]

Bash 没有列表,它有数组。

要检查数组是否包含值,请使用以下命令:

SERVNAME="ner"
SERVICE=("ner" "aks-gpu-ner-0306210907" "aks-gpu-ner-30012231" "aks-gpu-ner-1305211336")

if [[ " ${SERVICE[*]} " =~ " ${SERVNAME} " ]]; then
    echo "Match Found For Service: $SERVNAME"
else
    echo "Match Not Found For Service: $SERVNAME"
fi

假设 az ml 命令 returns 一个 json 数组字符串并且你想要 检查数组是否包含变量 SERVNAME 的值,你会吗 请尝试:

SERVNAME="ner"
SERVICE='[ "ner", "aks-gpu-ner-0306210907", "aks-gpu-ner-30012231", "aks-gpu-ner-1305211336"]'

if [[ $SERVICE =~ "\"$SERVNAME\"" ]]; then
    echo "Service Found"
    # put your command here to update the service
else
    echo "Service Not Found"
    # put your command here to deploy new service
fi

正则表达式运算符 $SERVICE =~ "\"$SERVNAME\"" 匹配字符串 $SERVICE 包含用双引号括起来的子字符串 $SERVNAME

如果jq可用,您还可以说:

result=$(echo "$SERVICE" | jq --arg var "$SERVNAME" '. | index($var)')
if [[ $result != "null" ]]; then
    echo "Service Found"
else
    echo "Service Not Found"
fi