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?
Best Answer
Bash functions are not like functions on other programming languages, they are more like commands. This means they have no classical return value, but
an exit/return code. This is an integer number in the range 0-255, where 0 means "success" and every other value represents an error. If you try to specify a number outside this range, it will be taken modulo 256 (add or subtract 255 from your number until it fits the range 0-255).
This code is automatically set to the return code of the last statement that got executed inside the function, unless you manually set it using the
return
command, like this:output streams. Each Bash function can write arbitrary strings to the output streams (STDOUT and STDERR), just like normal scripts. The output can either be directly from the commands you run in the function, or set manually by using
echo
.But instead of letting this output get displayed in the console, you can capture it when you run the function, e.g. using Bash's command substitution syntax, and store it in a variable in your main script:
So your code would have to look like this:
See Return value in bash script (on Stack Overflow) for more info.