Home > OS >  Compare String with list of strings in bash
Compare String with list of strings in bash

Time:10-12

I am trying to compare the service with a list of available service names, if service is found in the list then do update the service otherwise deploy the service. But below condition only deploying new service even when service available in list variable?

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

Example list

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

CodePudding user response:

Bash doesn't have lists it has arrays.

To check if array contains a value use the following:

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

CodePudding user response:

Assuming the az ml command returns a json array string and you want to check if the array includes the value of variable SERVNAME, would you please try:

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

The regex operator $SERVICE =~ "$SERVNAME" matches if the string $SERVICE contains the substring $SERVNAME enclosed with double quotes.

If jq is available, you could also say:

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