1

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

3
  • Your mention of a previous question should be a link (you can edit the question and fix it, explained in the help) to help with context. But, just looking at the short piece you show, I see that you set a variable called array_length to a list of file names and then try to use it as a number. Unless fileNames has only one element (in which case you wouldn't be using [0]) and it happens to be a number, that invocation of test can't possibly work. Commented Jul 15, 2016 at 3:01
  • Sorry about that, I'll try to find it again. Didn't help me so I closed it. Commented Jul 15, 2016 at 3:03
  • See bash arrays Commented Jul 15, 2016 at 4:10

1 Answer 1

6
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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I'll accept it in 5 minutes. Can you also tell me what's wrong with this: "$COUNTER + 1" -lt "$array_length" This one still gives an error, if any major concept, I'll open a new question.
@BhavyaArora : counter+1 will not increment counter.
I don't want to increment it here, just want to compare it with the next number. How do I remove the error. And also what would increase the counter? let counter = counter + 1 ?
@BhavyaArora : Not sure what you wisht exactly, See the edit.
@mklement0 : Thankyou and as always,appreciated :)

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.