Home > Back-end >  Bash For-Loop: How to compare two array items at different indexes?
Bash For-Loop: How to compare two array items at different indexes?

Time:11-12

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

CodePudding user response:

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
  • Related