In my script I want to count how many directories and files I have inside different directories. Inside "assignments" I have a lot of directories named "repo1", "repo2" etc. Here is my code:
ls -1 assignments | while read -r repoDir
do
find assignments/"$repoDir" | grep -v .git | grep "$repoDir"/ | while read -r aPathOfRepoDir
do
BASENAME=`basename "$aPathOfRepoDir"`
if [[ -d "$aPathOfRepoDir" ]]; then
totalDirectories=$((totalDirectories+1))
elif [[ -f "$aPathOfRepoDir" ]] && [[ "$BASENAME" == *".txt" ]]; then
totalTextFiles=$((totalTextFiles+1))
else
totalOtherFiles=$((totalOtherFiles+1))
fi
done
echo "total directories: $totalDirectories"
echo "total text files: $totalTextFiles"
echo "total other files: $totalOtherFiles"
totalDirectories=0
totalTextFiles=0
totalOtherFiles=0;
done
When the while-loop is finished I lose the values of those 3 variables. I know that this is happening because the while-loop is a sub-shell but I don't know how can I somehow "store" the values of the variables for the parent shell. I thought about printing those messages inside the while-loop when I know that it's the last "aPathOfRepoDir" but that's kinda a "cheap" way to do it and won't be efficient. Is there another way?
Thanks in advance