Bhavya Arora Bhavya Arora - 4 months ago 29
Bash Question

Integer Expression Expected : Bash

I read on stack overflow that we need quotes here and added quotes, but it ddn't helped.

array_length=${fileNames[@]}

COUNTER=0

while [ "$COUNTER" -lt "$array_length" ]; do


I get the error still. Please help. Completely new to bash

Answer
array_length=${fileNames[@]}

should have been

array_length=${#fileNames[@]}

For the expected behaviour, your while loop should be:

while [ "$COUNTER" -lt "$array_length" ]
do
.
#do something
.
((COUNTER++)) # Equivalent to COUNTER=COUNTER+1
done

${fileNames[@]} expands to the whole array while prefixing it with # gives you the number of elements.


Sidenotes:

1. Don't forget to increment COUNTER inside while loop.
2. Try avoiding capitalized variables like COUNTER as they are usually reserved for the system.