Finding string in BASH array

November 5, 2018

I had a need to go through an array variable in bash and see if certain strings were present in the specified order. The existing code looked for values at specific array indexes, but this was deemed too fragile. The fix was to make sure that the strings were present, but without caring if there were other values between them.

#!/bin/bash

declare -a g_ErrorLogsArray=("text5" "text6" "text7" "text8")

assertNext()
{
  local -r lookingFor=$1
  echo "Looking for ${lookingFor}"

  while [[ ${#g_ErrorLogsArray[@]} -gt 0 ]]; do
    if [ "${g_ErrorLogsArray[0]}" = "${lookingFor}" ]; then
      echo "Array starts with ${lookingFor}"
      # removing item that was found from start of array
      g_ErrorLogsArray=("${g_ErrorLogsArray[@]:1}")
      echo "Found, array is now: ${g_ErrorLogsArray[*]}" 
      return
    fi
    # removing non-matching item from start of array
    g_ErrorLogsArray=("${g_ErrorLogsArray[@]:1}")
    echo "Not found, reducing array by one element: ${g_ErrorLogsArray[*]}"
  done
  echo "Fail, ran off end of array"
}

assertNext "text5"
assertNext "text7"