2
salary=(30000 45000 15000 40000)
average=37500
ans=0
for i in ${salary[@]}
do
  if [ $((i<average)) ]
  then
    ans=$((ans+1))
  fi
done
echo $ans

I am traversing through the salary array using for-loop, inside the for-loop, there is an if condition.

There are only two fields in array that suits if [ $((i<average)) ] condition, 30000 and 15000.

But it showing 4

Expected output is 2

0

1 Answer 1

5

The extra [..] over the arithmetic evaluation is redundant. The presence of it "forces" a string evaluation of the result of the arithmetic evaluation. Either of "0" or "1" from the $((..)) is evaluated as [ -n 0 ] and [ -n 1 ] which is always true.

So just use the arithmetic operator alone or use the arithmetic comparator inside [..], i.e.

if (( i < average )); then

or

if [ "$i" -lt "$average" ]; then
Sign up to request clarification or add additional context in comments.

Comments

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.