Friday, July 29, 2022

[SOLVED] Check shell variable failing when it returns null list

Issue

Objective: Trying to check if resource exist on azure with bash script

Code that I use :

status=$(az group list --query "[?name.contains(@,'test')]")
if [[ "$status" == null ]];
then
   echo "not exist"
else
   echo "exist"
fi

I have this resource in azure i.e it should return as "exist" however its says not exist If I change to a non existant resource group name then time also its gives not exist.

do you see any syntax issue here ?

Instead of script if I execute at commmand line to check , below are results

user@ablab:~$ status=$(az group list --query "[?name.contains(@,'abcd')]")
user@ablab:~$ echo $status
[]
user@ablab:~$ status=$(az group list --query "[?name.contains(@,'test')]")
user@ablab:~$ echo $status
[ { "id": "/subscriptions/xxxx-xxxx-xxx--xxxxx3/resourceGroups/test1", "location": "westeurope", "managedBy": null, "name": "test1", "properties": { "provisioningState": "Succeeded" }, "tags": null, "type": "Microsoft.Resources/resourceGroups" } ]

Now I wanna use if condition, so that if its exist it should process set of flow else set of code..

Please let me know what wrong with my if statement.


Solution

The syntax is fine. However, I don't see from your example, that az would write the string null to stdout. In the first case, it prints, according to what you posted, the string []. To catch this case, you would have to test

if [[ $status == '[]' ]]
then
  ...

The quotes around the string tell bash to not interpret it as a glob pattern.



Answered By - user1934428
Answer Checked By - Terry (WPSolving Volunteer)