Reputation: 99
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!
Upvotes: 1
Views: 32
Reputation: 113844
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.
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.
Upvotes: 1
Reputation: 2081
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)
Upvotes: 1