Search code examples
arraysshelliterationnested-loopsunset

Nested for loop behavior - shell script


There are two shell script arrays. For demonstration purposes the first array holds two elements. These two elements will also be in the second array with the addition of another array.

The purpose of this nested for loop is to remove the matching strings from the second array. So, at the end the third element should be the only element still within the second array.

I believe that:

  • My syntax / algorithm with the for loops is skipping an iteration
  • My understanding of the method of unset array is incorrect

Please note that i want to completely remove the element and not just leave an element empty.

CODE

first_string='first'
second_string='second'
third_string='third'

strings_to_remove=()
strings_to_remove+=("$first_string")
strings_to_remove+=("$second_string")

main_array=()
main_array+=("$first_string")
main_array+=("$second_string")
main_array=("$third_string")

for i in "${main_array[@]}";    do
    echo $i
done

echo ''

for r in "${!strings_to_remove[@]}"; do
  index=''
  for i in "${!main_array[@]}"; do
    if [[ "${main_array[$i]}" = "${strings_to_remove[$r]}" ]];  then
      index=$i
    fi
  done
  if [[ $index -ne '' ]]; then
    unset main_array[$index]
    main_array=( "${main_array[@]}" )
  fi
done

echo ''

for i in "${main_array[@]}";    do
    echo "$i"
done

OUTPUT

first
second
third

first
third

The first and second element should be removed, however only the second is removed. I am unsure whether the algorithm itself or the syntax is incorrect.


Solution

  • The problem is here:

    [[ $index -ne '' ]]
    

    This is doing an arithmetic test, and [[ 0 -ne '' ]] return false. Change from:

    index=''
    ...
    if [[ $index -ne '' ]]; then
    

    to:

    index=-1
    ...
    if [[ $index -ge 0 ]]; then
    

    and you are done.