Ubuntu – Why does `ls -l` count more files than me

command linefilesls

Apparently I cannot count. I think there are three files in /media

$ tree /media
├── foo
├── onex
└── zanna
3 directories, 0 files

However, ls -l finds 12.

$ ls -l /media
total 12
drwxr-xr-x  2 root root 4096 Jul 31 20:57 foo
drwxrwxr-x  2 root root 4096 Jun 26 06:36 onex
drwxr-x---+ 2 root root 4096 Aug  7 21:17 zanna

And, if I do ls -la I get only . and .. in addition to the above, but the count is total 20

What's the explanation?

Best Answer

The 12 you see is not the number of files, but the number of disk blocks consumed.

From info coreutils 'ls invocation':

 For each directory that is listed, preface the files with a line
 `total BLOCKS', where BLOCKS is the total disk allocation for all
 files in that directory.  The block size currently defaults to 1024
 bytes, but this can be overridden (*note Block size::).  The
 BLOCKS computed counts each hard link separately; this is arguably
 a deficiency.

The total goes from 12 to 20 when you use ls -la instead of ls -l because you are counting two additional directories: . and ... You are using four disk blocks for each (empty) directory, so your total goes from 3 × 4 to 5 × 4. (In all likelihood, you are using one disk block of 4096 bytes for each directory; as the info page indicates, the utility does not check the disk format, but assumes a block size of 1024 unless instructed otherwise.)

If you want to simply get the number of files, you might try something like

ls | wc -l