kodie
8/25/2016 - 4:18 PM

Searches array for a string and returns it's position/key if found.

Searches array for a string and returns it's position/key if found.

function arraySearch {
  local i
  local output
  local a=("$@")
  local last_idx=$((${#a[@]} - 1))
  local b=${a[last_idx]}
  unset a[last_idx]

  for i in "${!a[@]}" ; do
    if [ "${a[$i]}" == "$b" ]; then
      output=$i
    fi
  done

  echo $output
}

# Example
array=("test1" "test2" "test3" "test4")
key=$(arraySearch "${array[@]}" "test3")
echo $key

# Output: 2