executing command from subdirectories

Hello,

I've been trying to run 'ls -1R | wc -l' inside of sub directories to in order to determine how big each folder is.

find . -maxdepth 1 -type d | while read folder

 do
    cd "$folder" &&
        echo "$folder has $(ls -1R | wc -l) files" &&
    cd ..
 done

or

for folder in `ls -1S`; do 
    cd "$folder" &&
        NUMFILES=$(ls -1R | wc -l)
        FOLDERLIST='  $folder contains $NUMFILES files.'
    echo $FOLDERLIST >> ../filelist.txt && 
    cd ..
done

I know the second one works as long as I ignore the errors, but it does not work with directory names with spaces.

Hi.

Try putting quotes (") around the `ls -1S` part.

Better is not to use this style, but

ls -1S | while read folder; do
...

With the style you chose, you're at the mercy of how long your arg list can be. With read, you are not.

Also with "read folder" the space problem is not an issue.

To get rid of the errors direct them to /dev/null

cd $folder 2> /dev/null

Or better perhaps

cd $folder 2> /dev/null || continue

Maybe use this?

function my_function
{
    for file_or_directory in *;do
        [[ -d "${file_or_directory}" ]] && {
            cd "${file_or_directory}"
            count_files_in_any_way_since_there_are_many_ways
            cd "${OLDPWD}"
            my_function
        }
    done
    return 0
}

Thanks adderek. Your solution fixed everything.

Here is the final code:

for file_or_directory in *;do
[[ -d "${file_or_directory}" ]] && {
    cd "${file_or_directory}"
    echo "${file_or_directory} has $(ls -1R | wc -l) files"
    cd "${OLDPWD}"
}
done

and outputs:

clients has 7099 files
current projects has 1230 files
orgainise has 1733 files
toserver has 60203 files
webiste stuff has 831 files