6

variable to continue counting the count in the loop and printing a total at the...

 2 years ago
source link: https://www.codesd.com/item/variable-to-continue-counting-the-count-in-the-loop-and-printing-a-total-at-the-end.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

variable to continue counting the count in the loop and printing a total at the end

advertisements

I'm new to scripting and I'm trying to make a script to count files in each folder (and sub-folders) of the current directory.

This script seems to be working OK:

for dir in $( ls -pa | grep / | tail -n +3 ); do
    echo "${dir%/}: $( find ${dir} -type f | wc -l )"
done

But, I'd like to print the total number of files after the for loop without inefficiently using the find command to count the total.

I've tried a few things with no success.

for dir in $( ls -pa | grep / | tail -n +3 ); do
     echo "${dir%/}: `count=`$( find ${dir} -type f | wc -l )"
     total=$((total+count))
done 

echo "total: $total"

Not sure if my command substitution is correct and would appreciate someone pointing me in the right direction! Thanks


What's wrong with your code is count variable is not set correctly.

echo "${dir%/}: `count=`$( find ${dir} -type f | wc -l )"

In the line, count= is command substitution which results in nothing. So count won't be set because there is no assignment statement but a command substitution and another command substitution.
So here is the solution:

for dir in $( ls -pa | grep / | tail -n +3 ); do count=$( find ${dir} -type f | wc -l ); echo "${dir%/}: $count"; total=$((total+count)); done; echo "total: $total"


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK