Linux – EXT3: If block size is 4K, why does ls -l show file sizes below that

ext3filesystemslinuxls

If you run ls -l on a file that contains one letter, it will list as 2B in size. If your file system is in 4k blocks, I thought it rounded files up to the block size? Is it because ls -l actually reads the byte count from the inode? In what circumstances do you get rounded up to block answers vs actual byte count answers in Linux 2.6 Kernel GNU utils?

Best Answer

I guess you got that one letter into the file with echo a > file or vim file, which means, you'll have that letter and an additional newline in it (two characters, thus two bytes). ls -l shows file size in bytes, not blocks (to be more specific: file length):

$ echo a > testfile
$ ls -l testfile
-rw-r--r-- 1 user user 2 Apr 28 22:08 testfile
$ cat -A testfile
a$

(note that cat -A displays newlines as $ character)

In contrast to ls -l, du will show the real size occupied on disk:

$ du testfile
4

(actually, du shows size in 1kiB units, so here the size is 4×1024 bytes = 4096 bytes = 4 kiB, which is the block size on this file system)

To have ls show this, you'll have to use the -s option instead of/in addition to -l:

$ ls -ls testfile
4 -rw-r--r-- 1 user user 2 Apr 28 22:08 testfile

The first column is the allocated size, again in units of 1kiB. Last can be changed by specifying --block-size, e.g.

$ ls -ls --block-size=1 testfile
4096 -rw-r--r-- 1 aw aw 2 Apr 28 22:08 testfile
Related Question