Advanced use of az-cli in bash

Using If Then Else to determine if variable is null

if [ $resourceGroup != '' ]; then
   echo $resourceGroup
else
   resourceGroup="msdocs-learn-bash-$randomIdentifier"
fi

Using If Then to create or delete a resource group

if [ $(az group exists --name $resourceGroup) = false ]; then 
   az group create --name $resourceGroup --location "$location" 
else
   echo $resourceGroup
fi
if [ $(az group exists --name $resourceGroup) = true ]; then 
   az group delete --name $resourceGroup -y # --no-wait
else
   echo The $resourceGroup resource group does not exist
fi

Using Grep to determine if a resource group exists, and create the resource group if it does not

az group list --output tsv | grep $resourceGroup -q || az group create --name $resourceGroup --location "$location"

Using CASE statement to determine if a resource group exists, and create the resource group if it does not

var=$(az group list --query "[? contains(name, '$resourceGroup')].name" --output tsv)
case $resourceGroup in
$var)
echo The $resourceGroup resource group already exists.;;
*)
az group create --name $resourceGroup --location "$location";;
esac

Last updated