I have the following function to count the number of files in a directory, within my bash script.
file_count() {
no_of_files=$(find "$1" -maxdepth 1 -type f -printf '.' | wc -c)
}
I'd like to use it repeatedly on different directories and save the count into a variable for each directory. Currently to do this, I use
file_count $somedir
files_in_somedir="$no_of_files"
I'm aware that I'm setting the no_of_files
variable outside of the function each time, and would like to make it local to the function, not settign an intermediate variable in the main script. This is just in case there's some mistake meaning that the variable doesn't change between calls of the function (mistyping the function name maybe), and the old value of no_of _files
is used.
If my function were:
file_count() {
local no_of_files=$(find "$1" -maxdepth 1 -type f -printf '.' | wc -c)
}
How would I easily set these directory count variables?
return
keyword, but something doesn't seem to be working with my use of it.return "no_of_files"
at the end of the function, then reference it with$?
I get a completely spurious value.