0

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

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@TrungTrung See the link at the end of my answer.
2

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

2 Comments

The first one is not a problem. From man bash: "The subscript is treated as an arithmetic expression".
@TrungTrung You can find more information about conditional expressions here.
1

you should use -gt, greater than

1 Comment

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.