1

I am new to bash and scripting and I am trying to create a simple script but for some reason it won't let me run this:

fileCount= ls -1 | wc -l

#echo $fileCount

for (( i=0; i<$fileCount; ++i )) ; do
 echo item: $i
done

Whenever I try to run this it just gives me an error message saying it expected an operand. I am really confused on the error here and any help would be greatly appreciated!

1
  • Please post the entire error message you're getting. Commented Apr 10, 2015 at 19:37

2 Answers 2

1

To get your code running with minimal change, replace:

fileCount= ls -1 | wc -l

With:

fileCount=$(ls -1 | wc -l)

$(...) is called command substitution. It is what you use when you want capture the output of a command in a variable.

It is very important that there be no spaces on either side of the equal sign.

Improvements

  • To speed up the result, use the -U option to turn off sorting.

  • To prevent any attempt to display special characters, use -q.

Thus:

fileCount=$(ls -1Uq | wc -l)

Lastly, when ls is writing to something other than a terminal, such as, in this command, a pipeline, it prints one file name per line. This makes -1 optional.

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

Comments

1

you missed to assign the output of wc -l to your variable. Try this:

fileCount=$(ls | wc -l)

(option "-1" is not needed, because ls writes one file per line if its stdout is not a terminal)

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.