Du cannot access file – No such file or directory error

disk-usagerm

I have lots of subfolders inside a particular folder which in turn contains lots of smaller files. They are created programmatically and so I do not know how many of them are there inside.

I decided to remove all these sub-folder and files and so I issued the command,

rm -rf foldername/

However, the rm command is taking so much time to execute which I believe is perfectly normal since it has to unlink all the files.

But, I decided to check if the size of this folder is getting reduced by issuing the command,

du -sh foldername/

However, the above command gives me the error as,

du: cannot access `foldername/file': No such file or directory

Why is this error happening?

Best Answer

du, like any command that traverses directory trees recursively, operates in the following way:

  1. Read information about a file, accessed via its path¹. In the case of du, the system call stat provides the file type (in particular, whether it's a directory) and size. Initially, the names are taken from the command line.
  2. If the file is a directory, open it and read the list of file names.
  3. For each file name in the directory, construct a file path (DIRECTORY/ENTRY_NAME) and act on it recursively starting at step 1. This step may be performed partly in parallel with the previous one (it depends on the implementation).

rm is running and deleting files one by one. Occasionally, du reads a file name in step 2, but by the time it gets around to processing it in step 3, rm has deleted it. Whether you see this error at all and how many times depends on the relative speed of rm and du and is pretty much unpredictable.

¹ There are only two ways to directly access a file: by path (including directory information, relative or absolute), or (if the file is open) by descriptor.

Related Question