Search code examples
bashash

Bash compare strings not working inside of while loop


I created this bash script and can't seem to figure out why my code inside of the if block isn't executing.

db_instances_status="creating" 
db_instances_status=$(makes api request to get value)

COUNTER=0
while [ $COUNTER -lt 1 ]; do
  db_instances_status=$(makes api request to get value)

  echo "$db_instances_status" # echos available

  if [ "available" = "$db_instances_status" ]; then
     # code never makes it here
     dosomething()
     break;
  fi
  sleep 30
done

I followed examples from this How to compare strings in Bash

and here https://tecadmin.net/tutorial/bash/examples/check-if-two-strings-are-equal/


Solution

  • You either are not getting to the if statement or else the variable doesn't contain what you think it does.

    This snippet will help debug both...

    while [ $COUNTER -lt 1 ]; do
      echo "[DEBUG] getting status"
      db_instances_status=$(makes api request to get value)
      echo "[DEBUG] X${db_instances_status}X"
      echo "$db_instances_status" # echos available
    
      if [ "available" = "$db_instances_status" ]; then