totalNoob
totalNoob

Reputation: 39

how to compare array element of one array with elements in another array in bash?

I have stored some strings in array1, lets say

array1[0]=apple
array2[1]=orange

and array2 contains

array2[0]=apple
array2[1]=mango

I want to loop through each element and check if they match. I tried using this condition inside loop but it didnot work

if [ "$array[i]" = "$array2[j]" ]

Upvotes: 0

Views: 811

Answers (1)

Socowi
Socowi

Reputation: 27215

To access the elements of an array in bash you have to use ${array[i]} instead of just $array[i]. Because the [ cannot normally be part of a variable name, bash interprets $array[i] as ${array} followed by a literal [i].

By the way: https://www.shellcheck.net/ would have found this error.

Upvotes: 1

Related Questions