uttam
uttam

Reputation: 75

How to process value from for loop in shell

I have to a perform logic like this. I have a array. expression for this in shell

[(first no + arrlen) - ( index +1 ) - ge 10 ]

I have code this like this but it's not working

#!/bin/bash
array=(4 5 6 7 8 9)
for i in ${array[@]}
do
echo $i
done
echo "${#array[@]}"
l=${#array[@]}


    count=0
    for (( i=0; i < ${#array[@]}; i++ ))

     do
       if [ ($(`expr $i + $l`) - $(`expr ${!array[@]} + 1`)) -ge 10 ]
            then
            count=`expr $count + 1`
            else
            echo
       fi
    done

Upvotes: 0

Views: 54

Answers (1)

PesaThe
PesaThe

Reputation: 7499

Your code could look like this:

#!/bin/bash

array=(4 5 6 7 8 9)
for i in "${array[@]}"; do
    echo "$i"
done

length=${#array[@]}
first=${array[0]}
count=0
for (( i=0; i < length; i++ )); do
    if (( (first + length) - (i + 1) >= 10 )); then
        ((count++))
    else
        echo "something"
    fi
done
  1. Don't use expr, use (( )) for arithmetic expressions
  2. Quote expansions: "$i", "${array[@]}", ...
  3. ${!array[@]} expands to ALL indexes of your array, not the current index

Upvotes: 1

Related Questions