Answer the question
In order to leave comments, you need to log in
Function to calculate the average size of a file in a directory in Bash?
We need to write a function to calculate the average size of a file in a directory. In this case, the function should check the directory for existence, and then display the average size of files in the directory. You also need to exclude subdirectories and symbolic links from the calculations.
I hit a dead end, and I can’t go further than this function ...
stat -c '%F %s' /mydir/.* *
Answer the question
In order to leave comments, you need to log in
#!/bin/bash
# uncomment for debug
#set -x
function get_avg_size() {
[ ! -d "$1" ] && echo "Directory $1 DOES NOT exists." && exit 1
sum_size=0
count=0
for size in $(LC_ALL=C stat -c '%F %s' $1/* | grep 'regular file' | cut -d ' ' -f 3); do
let sum_size=$sum_size+$size
let count=$count+1
done
echo "Average file size $(($sum_size/$count))"
}
get_avg_size ~/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question