For the consistency check of a backup program, I want to define a function which counts all files in a directory including all files in subdirs, subsubdirs and so on.
The solution I am trying so far is as follows:
countfiles() {
local cdir=$1
local files=$(ls -la $cdir | grep -cv '^[dl]')
local dirstring=$(ls -la $cdir | grep '^d' | egrep -o ' \.?[^[:space:].][^[:space:]]+$')
local directories=(${dirstring//"\n"/})
echo ${directories[@]}
for dir in ${directories[@]}; do
echo -n "$dir "
echo -n 'filecount >> '
local dirfiles=$(countfiles "$cdir/$dir")
echo -n $dirfiles
echo ' <<'
#files=$(($files+$dirfiles))
done
echo $files
}
Which gives me the following output:
.config .i3 .scripts
.config filecount >> gtk-3.0 termite gtk-3.0 filecount >> 2 << termite filecount >> 2 << 1 <<
.i3 filecount >> 5 <<
.scripts filecount >> 2 <<
5
While the actualization of my $files
counter is commented atm and I may need to unlocalize it, right now I set all variables as local to avoid any interference.
The directory tree is as follows:
/.scripts/backup_dotfiles.sh
/.config/termite/config
/.config/gtk-3.0/settings.ini
/.i3/config
/.i3/i3blocks.conf
/.i3/lockicon.png
/.i3/lockscreen.sh
/.gtkrc-2.0
/.bashrc
/.zshrc
/.i3
/.Xresources
My questions:
- Why does it always count the files +1 except for the master directory?
- Why does it count anything in the '.config' directory, as there are no files in there?
- How can I fix this?