TrungTrung
TrungTrung

Reputation: 33

array in bash script

i have a below script:

for (( i=0; i <= ( ${#arr1[@]} - 1); i++ )); do
  if [[ ${arr1[i]} > 100 ]]; then 
    echo "=> x"
    iptables -A INPUT -s 192.168.162.1 -j DROP
    exit
  else
    echo "=> y"
  fi
done

In my array, no element > 100, all output must be "=> y". when arr1[i]=1, it's OK. output: "=> y" But when arr1[i]=5 or anything is not 1, it has a problem, output "=> x"

I think my problem is here if [[ ${arr1[i]} > 100 ]] but I dont know how to edit it. :(

Help me correct it . please . Thanks a lot

Upvotes: 0

Views: 74

Answers (4)

chepner
chepner

Reputation: 532418

Since you don't use i for anything other than subscripting the array, it will be simpler to iterate over the values of the array directly:

for value in "${arr1[@]}"; do
    if (( value > 100 )); then
        echo "=> x"
        iptables -A INPUT -s 192.168.162.1 -j DROP
        exit
    else
        echo "=> y"
    fi
done

This includes another option for correctly comparing two integer values, the ((...)) command, which provides a context where > can be used for numerical comparison instead of string comparisons.

Upvotes: 0

mVChr
mVChr

Reputation: 50205

You want either:

if (( ${arr1[$i]} > 100 )); then

or for POSIX shells that don't support (()), you can use:

if [[ ${arr1[$i]} -gt 100 ]]; then

Here is a good list of other comparison operators.

Upvotes: 4

ray
ray

Reputation: 4267

you should use -gt, greater than

Upvotes: 1

devnull
devnull

Reputation: 123668

There are two problems with what you've done:

  1. You need to say if [[ ${arr1[$i]} > 100 ]]; then (note that it should be $i instead of i).

  2. Saying if [[ ${arr1[$i]} > 100 ]]; is incorrect. This performs a lexicopgraphic comparison and isn't quite what is intended. Either say:

    if [[ ${arr1[$i]} -gt 100 ]]; then

    or

    if (( ${arr1[$i]} > 100 )); then

Upvotes: 2

Related Questions