Handle Azure CLI output on bash for az sql db list

Viewed 216

This instruction returns 1 if a database exists and 0 otherwise.

az sql db list --resource-group demo-group --server demo-server --query "[?name == 'debo-database'] | length(@)"

The problem is how to use this in if conditions like

[ $(az sql db list --resource-group demo-group --server demo-server --query "[?name == 'debo-database'] | length(@)") -eq 1 ] && echo "exists"

The above-mentioned condition doesn't work as planned...

1 Answers

You're mistakenly checking the stdout output of the command to be the value "1" instead of its return code. Use && conditional chaining for a non-zero return code (by inverting the sense of the original az return code with !):

! az sql db list --resource-group demo-group --server demo-server --query "[?name == 'debo-database'] | length(@)" && echo "exists"

... or the same thing but more verbosely with an if statement:

if ! az sql db list --resource-group demo-group --server demo-server --query "[?name == 'debo-database'] | length(@)"; then echo "exists"; fi

The above check for any non-zero return code from az. To check the return code more explicitly for being 1:

az sql db list --resource-group demo-group --server demo-server --query "[?name == 'debo-database'] | length(@)"
case $? in
  (1) echo "exists";;
esac
Related