There are two different issues.
The first one is you're not quoting your variables: this ultimately makes stat
fail for that reason:
search $1 $2 $3
should be search "$1" "$2" "$3"
;
for elem in $1/*
should be for elem in "$1"/*
;
owner=`stat --format "%s" $1`
should be owner=`stat --format "%s" "$1"`
;
size=`stat --format "%U" $1`
should be size=`stat --format "%U" "$1"`
;
search "$elem" $2 $3
should be search "$elem" "$2" "$3"
.
The second one is when an empty directory is reached during the recursion, the expansion of for element in $1/*
fails and the two stat
commands are called on /path/to/empty/directory/*
, which doesn't exist:
% bash script.sh /home/user user 0
stat: cannot stat ‘/home/user/Documenti/Musica/*’: No such file or directory
stat: cannot stat ‘/home/user/Documenti/Musica/*’: No such file or directory
stat: cannot stat ‘/home/user/Documenti/My Games/*’: No such file or directory
stat: cannot stat ‘/home/user/Documenti/My Games/*’: No such file or directory
stat: cannot stat ‘/home/user/Documenti/Video/*’: No such file or directory
stat: cannot stat ‘/home/user/Documenti/Video/*’: No such file or directory
stat: cannot stat ‘/home/user/home/user/*’: No such file or directory
stat: cannot stat ‘/home/user/home/user/*’: No such file or directory
stat: cannot stat ‘/home/user/Modelli/*’: No such file or directory
stat: cannot stat ‘/home/user/Modelli/*’: No such file or directory
stat: cannot stat ‘/home/user/Musica/*’: No such file or directory
stat: cannot stat ‘/home/user/Musica/*’: No such file or directory
stat: cannot stat ‘/home/user/Pubblici/*’: No such file or directory
stat: cannot stat ‘/home/user/Pubblici/*’: No such file or directory
stat: cannot stat ‘/home/user/Video/*’: No such file or directory
stat: cannot stat ‘/home/user/Video/*’: No such file or directory
%
One way to fix that would be checking whether the file / directory exists before calling display_owner_and_size
, so that to skip the current iteration if we're attempting to stat / traverse a directory that doesn't exist (since the directory is empty there's no reason to stat
its content nor to keep traversing that branch of the tree):
[ -e "$elem" ] && display_owner_and_size "$elem" || continue
Adding to that, other errors are:
owner=`stat --format "%s" "$1"`
should be owner=`stat --format "%U" "$1"`
and size=`stat --format "%U" "$1"`
should be size=`stat --format "%s" "$1"`
;
- You can't use
>
to make numerical comparisons. Use -gt
: if [[ $owner == $2 && $size -gt $3 ]]
.
So the corrected script would be:
#!/bin/bash
owner="valdsilviufarcas"
size=0
function display_owner_and_size()
{
owner=`stat --format "%U" "$1"`
size=`stat --format "%s" "$1"`
}
function search()
{
for elem in "$1"/*
do
[ -e "$elem" ] && display_owner_and_size "$elem" || continue
if [[ $owner == $2 && $size -gt $3 ]]
then
echo $elem
fi
if test -d "$elem"
then
search "$elem" "$2" "$3"
fi
done
}
search "$1" "$2" "$3"