How to compare array elements in BASH?

I've got an array a and b, and I need the correct bash syntax to compare array elements in this for loop:

for ((x=0;x<10;x++)); do
    if [ "$a[$x+1]" -gt "$a[$x]" ]; then
        $b[x+1]=1
    if [ "$a[$x+1]" -lt "$a[$x]" ]; then 
        $b[x+1]=0
    fi

How do I get bash to correctly assign a value of 1 to array element b[x+1] when the array element a[x+1] is greater than a[x]?

So if array element a[1] is greater than a[0], then b[1]=1?

An easier way to ask this question, and that would be more simple, would be:

How do I have it know if array element 1 is greater than 0?

 if [ "$a[1]" -gt "$a[0]" ]; 
 then
 echo element 1  greater than element 0
 fi

The above code gives UNEXPECTED END OF FILE, as if I'm missing some syntax. Anyone know this BASH syntax?

UPDATE: So this is the script file:

 #!/bin/bash
 declare -a a
 declare -a b
 readarray a < arraydatafile 

 for ((x=0;x<5;x++)); 
 do
 if [ "${a[$x+1]}" -gt "${a[$x]}" ]; 
 then  
 b[x+1]=1   
 fi
 done

arraydatafile:

 1
 2
 1
 4
 5
 4
 2
 8

root@debian:/home/l0l/Documents/# bash script

script line 8: [: 2 : integer expression expected script: line 8: [: 1 : integer expression expected script: line 8: [: 4 : integer expression expected script: line 8: [: 5 : integer expression expected script: line 8: [: 4 : integer expression expected

Anyone know the exact syntax?

2 answers

  • answered 2018-01-14 06:47 jas-

    I think your conditional and assignment is incorrect;

    Try... $a[$(($x+1))]

    And...

    $b[$(($x+1))]=1

  • answered 2018-01-14 06:47 Cyrus

    I suggest this syntax:

    if [ "${a[$x+1]}" -gt "${a[$x]}" ]; then  # with { and }
      b[x+1]=1                                # without $