0

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
7
  • anyone can help me out. Commented Jan 8, 2018 at 10:44
  • try this : if [ $(($(expr $i + $l) - $(expr ${!array[@]} + 1))) -ge 10 ] Commented Jan 8, 2018 at 10:54
  • it's not working Commented Jan 8, 2018 at 11:05
  • Can you add your array in the code ? So we can test the whole thing Commented Jan 8, 2018 at 11:08
  • yes ,i have added. Commented Jan 8, 2018 at 11:14

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

fist no is 1st element of array and and since i need indexes in loop.
@uttam What exactly is not working? It does the logic you described.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.