Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/bash

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading