Reputation: 1
I have an issye with my script. I have to write a script which collects information about each subfolder in the folder given as an argument, including: the name of the subfolder and the number of files in it (ls ... |wc -l
).
That's what I tried... But it doesn't search in one folder but in all of these.
#!/bin/bash
read $name
for i in $name/*;
do
[ -d "$i" ] && echo ${i##*/} $(ls -l "$i" | wc -l);
done
Upvotes: 0
Views: 848
Reputation: 3144
In general you don't want to parse the output of ls in a script. Perhaps try something like this:
#!/bin/bash
read name
shopt -s nullglob
for i in "${name}"/* ; do
if [[ -d "${i}" ]] ; then
i_files=( "${i}"/* )
echo "${i##*/}" "${#i_files[@]}"
fi
done
This puts the list of files in each directory into an array, then prints the length of the array. shopt -s nullglob
is necessary to ensure that the array is empty if there are no files inside the directory, otherwise the array will be length 1 and contain the unmatched glob in its unexpanded form.
Upvotes: 2