1

In my code I am basically looping recursively through all files and getting the sizes using stat -c%s $i. It works well for 99% of files, however, sometimes I get an error:

stat: cannot stat '/media/root/persistence/.Trash-0/info/subory': No such file or directory

When I navigate to /media/root/persistence/ directory and type ls, the ./Trash-0 folder is not shown, so I suppose the folder itself and it's content is hidden. How can I get rid of such error message and get size of files inside?

  • 1
    Please be aware that when you do an ls in a dir. then all the dot aka, hidden files are not listed. You should rather do: ls -al – user218374 Mar 24 '17 at 17:02
1

stat has no problem operating on hidden files. It is the usual convention on Unix-like systems for programs to ignore files and directories starting with a . by default, but it doesn't prevent those programs from seeing or acting on such files if they are explicitly specified.

The error means exactly what it says; stat tried to operate on a file or directory that does not exist. This is most likely because your code generated a file listing first, then while iterating over the list, .../info/subory was deleted or renamed or moved before your code could get to it.

Given the name of the parent directory, it's probably something as simple as the trash on your desktop being emptied while your code was running, either manually or through some automated process.

For transient problems like this, the simplest solution is to simply ignore the error, and maybe skip to the next loop iteration:

stat -c%s $i 2>/dev/null || continue

Or assign a default value (using -1 to signal that something went wrong, since 0 would be a valid size):

size=$(stat -c%s $i || echo -1)

You could also check for the file or directory's existence before running stat:

test -e $i && stat -c%s $i

Or use some combination of these techniques.

1

try this it show all files ".*" to show hidden files and "*" to show not hidden files

stat -c%s .* *

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.