0

I am doing bash and I was looking at a problem for array comparison and this was the solution below. I was wondering why they have the do in=false

#!/bin/bash
# enter your array comparison code here
# initialize arrays a b c
a=(3 5 8 10 6) 
b=(6 5 4 12) 
c=(14 7 5 7)
#comparison of first two arrays a and b
for x in "${a[@]}"; do 
  in=false 
  for y in "${b[@]}"; do 
    if [ $x = $y ];then 
      # assigning the matching results to new array z
      z[${#z[@]}]=$x
    fi
  done 
done
#comparison of third array c with new array z
for i in "${c[@]}"; do 
  in=false
  for k in "${z[@]}"; do
    if [ $i = $k ];then
      # assigning the matching results to new array j
      j[${#j[@]}]=$i
    fi
  done 
done 
# print content of array j
echo ${j[@]}

So should look like this correct? The first for loops do blank then the others analyze the arrays.

#!/bin/bash
a=(3 5 8 10 6) 
b=(6 5 4 12) 
c=(14 7 5 7)
#comparison of first two arrays a and b
for x in "${a[@]}"; do 

  for y in "${b[@]}"; do 
    if [ "$x" = "$y" ];then 
      # assigning the matching results to new array z
      z+=("$x")
    fi
  done 
done
#comparison of third array c with new array z
for i in "${c[@]}"; do 

  for k in "${z[@]}"; do
    if [ "$i" = "$k" ];then
      # assigning the matching results to new array j
     j+=("$i")
    fi
  done 
done 
# print content of array j
echo ${j[@]}
JEllis
  • 1
  • 2
  • 3
    There is no reason to do that. Ask the author of the code. Notes: qoute variables `"$x"` and just `j+=("$i")` to add to an array, it is easier to type then `j${#j[@]}]=`. – KamilCuk Jan 10 '22 at 15:54
  • I was confused as well. I found it to be unnecessary. It was actually from this website and this exercise https://www.learnshell.org/en/Array-Comparison. But the first for is to analyze the first array correct then the next one goes through the second array. I found this example very confusing. Thank you for your help @KamilCuk – JEllis Jan 10 '22 at 15:58
  • 1
    Thank you everyone I thought the code looked incorrect and had extra unnecessary steps. – JEllis Jan 10 '22 at 16:17
  • let z+=("$x") is the way to do math in bash – Christopher Hoffman Jan 11 '22 at 01:25

0 Answers0