16

I can use ls -l to get the logical size of a file, but is there a way to get the physical size of a file?

1
  • Please, define what you mean by "physical" size. Apr 9 '18 at 7:35
36

ls -l will give you the apparent size of the file, which is the number of bytes a program would read if it read the file from start to finish. du would give you the size of the file "on disk".

By default, du gives you the size of the file in number of disk blocks, but you may use -h to get a human readable unit instead. See also the manual for du on your system.

Note that with GNU coreutil's du (which is probably what you have on Linux), using -b to get bytes implies the --apparent-size option. This is not what you want to use to get number of bytes actually used on disk. Instead, use --block-size=1 or -B 1.

With GNU ls, you may also do ls -s --block-size=1 on the file. This will give the same number as du -B 1 for the file.


Example:

$ ls -l file
-rw-r--r--  1 myself wheel  536870912 Apr  8 11:44 file

$ ls -lh file
-rw-r--r--  1 myself wheel   512M Apr  8 11:44 file

$ du -h file
24K    file

$ du -B 1 file
24576   file

$ ls -s --block-size=1 file
24576 file

This means that this is a 512 MB file that takes about 24 KB on disk. It is a sparse file (mostly zeros that are not actually written to disk but represented as logical "holes" in the file). Sparse files are common when working with pre-allocated large files, e.g. disk images for virtual machines or swap files etc. Creating a sparse file is quick, while filling it with zeros is slow (and unnecessary).

See also the manual for fallocate on your Linux system.

5
  • in which case this difference is important? can you make a practical example? thank you in advance. Apr 8 '18 at 9:56
  • 1
    @D'ArcyNader See updated answer.
    – Kusalananda
    Apr 8 '18 at 10:10
  • Correct me if I misunderstand something, but it appears the first sentence is the other way around: stackoverflow.com/a/31437673/3701431 du would show how much data can be actually read, while ls shows the extent to which disk sectors are allocated. Jan 15 '19 at 23:46
  • 2
    @SergiyKolodyazhnyy (sorry to reply late) No, du shows the amount of disk actually in use by the file, while the apparent size (logical size) shown by ls is how many bytes a program would be able to read from it. If the file is sparse, some of the read bytes would be zeroes, but they would still be delivered to the program that read them (just not from disk).
    – Kusalananda
    Mar 14 '19 at 13:27
  • This was a really good answer.
    – Lizardx
    Jan 4 '20 at 0:23
5

I get the file size in bytes like this:

actualsize=$(du -b "${file}" | cut -f 1)

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.