# Comparing Negative values in bash using arrays

I do have a interesting problem that I am trying to tackle but I am yet unable to do so.

Let suppose that I have 2 arrays.

Array One:

``````1 -2 3 -2 2 -4
``````

Array Two:

``````-2 -3 4 5 2 -5
``````

I want to be able to actually compare the i-th value of both `Array one` and `Array two`:

• If both are negative then I would input in `Array Three` `0`
• If they are both positive I will add a `1`
• If they are opposites I need to insert a `2`

Output:

``````2 0 1 2 1 0
``````

How can I do that ?

• What if an element is zero? – Kusalananda Jul 10 '16 at 15:54
• Hello, a element can never be 0 since the two arrays are actually stock values so if both are up together then there is a relation down as well so the value can never be 0 am very new to bash – JavaFreak Jul 10 '16 at 15:55
• Really, don't use bash for this. Use Python or Perl, not bash. – cat Jul 10 '16 at 17:32

If you're familiar with C, C++ or Java, then you'll find this variant of `bash`'s `for`-loop quite familiar too. `bash` does arithmetic evaluation with `(( ... ))` so we'll use that when comparing values:

``````array1=(  1 -2  3 -2  2 -4 )
array2=( -2 -3  4  5  2 -5 )

array3=( )

for (( i=0; i < \${#array1[@]}; ++i )); do
if (( array1[i] < 0 && array2[i] < 0 )); then
array3[\$i]=0
elif (( array1[i] > 0 && array2[i] > 0 )); then
array3[\$i]=1
else
array3[\$i]=2
fi
done

echo "\${array3[@]}"
``````

This also works well with the `ksh93` shell, from which `bash` got many of its features.

A straight way:

``````arr1=(1 -2 3 -2 2 -4)
arr2=(-2 -3 4 5 2 -5)

i=0

while [[ "\$i" -lt "\${#arr1[@]}" ]]; do
a=\$(( \${arr1[\$i]} * \${arr2[\$i]} ))
if [[ "\$a" -lt 0 ]]; then
echo 2
else
if [[ "\${arr1[\$i]}" -gt 0 ]]; then
echo 1
else
echo 0
fi
fi
: "\$((i = i + 1))"
done | paste -sd ' ' -
``````
• Slightly obfuscated in a backhand trick shot kind of way, but +1 for creative use of `paste` and `:`. – Kusalananda Jul 10 '16 at 16:25