Kusku
Kusku

Reputation: 3

Bash For-Loop: How to compare two array items at different indexes?

I'm new to bash scripting and trying to compare two items of an array (specifically the $@ parameters). However, I just can't get it to work.

So what I'm specificially trying to do here is using a for loop to go through the $@ array, and compare the array item at index i with the item at index i+1. Unfortunately, ${@[$i]} and ${@[$i+1]} both cause bad substitution errors and I just can't seem to find the solution.

If anyone has an idea how this issue could be solved I'd be very grateful.

#!/bin/bash

for (( i = 0; i < ${#@}; i++ )); do
  if (( "${@[$i]}" < "${@[$i+1]}" )); then
    echo "true"
  fi
done

Upvotes: 0

Views: 363

Answers (2)

glenn jackman
glenn jackman

Reputation: 246837

indirect variables can also be used here:

for ((i=1, j=2; j <= $#; i++, j++)); do
    if (( ${!i} < ${!j} )); then
        echo "$i, $j: true"
    fi
done

given

set -- 2 4 6 8 1 10

we get

1, 2: true
2, 3: true
3, 4: true
5, 6: true

ref: 3.5.3 Shell Parameter Expansion


Or, we can destructively iterate over the positional params:

prev=$1
shift
while (($# > 0)); do
    curr=$1
    shift
    ((prev < curr)) && echo true
    prev=$curr
done

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141095

So use an actual array. $@ is not an array, it's special. Also, no need for ${ everywhere.

array=("$@")

...
   if (( array[i] < array[i+1] )); then

Upvotes: 2

Related Questions