Compare two arrays by values [BASH]

I have 2 arrays of values for example

A1 ={10 15 3 21}
A2 ={10 15 3 22}

I need to check which one has greater values. However:

A1 ={10 15 3 21}
A2 ={10 15 3 21 3} - this one would be greater.

A1 ={10 15 5 21} - this one greater
A2 ={10 15 3 21}

Basically, I want to compare patch numbers. What would be the fastest way to do that?

Thanks in advance.

Hello Jutsimitsu,

Welcome to the forum, could you please see the option code tags while posting any post, as per forum rules which you agreed during the creation of your user account. Please put all kind of commands and cods into code tags. You can also use Preview post option to see how post looks like before posting it. Hope this helps you.

   Also kindly let us know the All in All Input as well as required Output for same, it will be helpful for us to guide you.

Thanks,
R. Singh

I'm afraid you can't escape comparing the arrays element by element, in e.g. a for loop. If you show us what you tried and where you got stuck, we'll be glad to help.

Thanks for response, edited first post with code tags.

What I want it to return is an array, either A1 or A2. As for input, it's just those two arrays. I mean it was in strings of 10.15.5.21 for example but I split it with IFS.

I thought as much as to compare those arrays in loop. I admit I am a C++ programmer, so bash scripting is quite uncommon for me. I got stuck quite early, with loop like:

for i in "${A1[@]}"
do
    if [ ${#A1[@]} -eq ${#A2[@]} ]; then
        echo "TRUE"
    else 
        echo "FALSE"
    fi
done

I don't know how to get an iterator for both arrays. Then check if array value is not null, then how to break if I find out which one is greater.

One way might be something like:

for ((i=0; i<${#A1[@]} || i<${#A2[@]}; i++))
do
  if (( ${A1:-0} > ${A2:-0} )); then
    echo A1
    break
  elif (( ${A1:-0} < ${A2:-0} )); then
    echo A2
    break
  fi
done

Try

echo "(" ${A1[@]} "), (" ${A2[@]} ")"
( 10 15 3 21 ), ( 10 15 3 20 )
LEN=${#A1[@]}; [ $LEN -lt ${#A2[@]} ] && LEN=${#A2[@]}
while [ 0$i -lt $LEN ]; do [ 0"${A1[$i]}" -gt 0"${A2[$i]}" ] && break; ((i++)); done; [ $i -eq $LEN ] && echo A2 || echo A1
A1

Thanks guys! That's exactly what I needed! Works miracles! :smiley: