Tuesday, October 4, 2011

Unix: Difference between 'du' and 'ls'

The following exercise was done on Linux box, using a filesystem which has the storage block size of 4096 bytes i.e.  1 block = 4096 bytes
Within an empty directory, I create 5 files of the following sizes:


5-bytes                 < 1 block
6-bytes                 < 1 block
4096-bytes          = 1 block
8192-bytes          = 2 blocks
9000-bytes          > 2 blocks  &  < 3 blocks

See command transcript below.

ramesh@linux:/tmp/trial$ dd if=/dev/zero of=5_bytes.txt bs=5 count=1
1+0 records in
1+0 records out
5 bytes (5 B) copied, 0.000121224 s, 41.2 kB/s
ramesh@linux:/tmp/trial$ dd if=/dev/zero of=6_bytes.txt bs=6 count=1
1+0 records in
1+0 records out
6 bytes (6 B) copied, 2e-09 s, 3.0 GB/s
ramesh@linux:/tmp/trial$ dd if=/dev/zero of=4096_bytes.txt bs=4096 count=1
1+0 records in
1+0 records out
4096 bytes (4.1 kB) copied, 0.000404249 s, 10.1 MB/s
ramesh@linux:/tmp/trial$ dd if=/dev/zero of=8192_bytes.txt bs=4096 count=2
2+0 records in
2+0 records out
8192 bytes (8.2 kB) copied, 0.000135646 s, 60.4 MB/s
ramesh@linux:/tmp/trial$ dd if=/dev/zero of=9000_bytes.txt bs=9000 count=1
1+0 records in
1+0 records out
9000 bytes (9.0 kB) copied, 0.000177566 s, 50.7 MB/s

 

ramesh@linux:/tmp/trial$ ls -ltr
total 32
-rw-r--r-- 1 ramesh users    5 2011-10-04 16:20 5_bytes.txt
-rw-r--r-- 1 ramesh users    6 2011-10-04 16:20 6_bytes.txt
-rw-r--r-- 1 ramesh users 4096 2011-10-04 16:20 4096_bytes.txt
-rw-r--r-- 1 ramesh users 8192 2011-10-04 16:21 8192_bytes.txt
-rw-r--r-- 1 ramesh users 9000 2011-10-04 16:25 9000_bytes.txt


The significance of the values in red from the the output of the command  ls -ltr  above is expounded below. The fifth column's values 5, 6, 4096, 8192 and 9000 indicate the total number of the bytes of the contents within the corresponding files.

The actual number of data blocks each file uses is:

File -- Block Count

5_bytes.txt -- 1 block
6_bytes.txt -- 1 block
4096_bytes.txt -- 1 block
8192_bytes.txt -- 2 blocks
9000_bytes.txt -- 3 blocks

The total count of blocks used by all the entries in the directory /tmp/trial is 8. As such, the total number of blocks used in terms of kilobytes is 8 x 4k = 32k. This is what the line total 32 makes known. Note that 1 kilo here refers to the value 1024 and not 1000.




ramesh@linux:/tmp/trial$ du *
4   4096_bytes.txt
4   5_bytes.txt
4   6_bytes.txt
8   8192_bytes.txt
12  9000_bytes.txt



du *  lists the directory entries along with their storage blocks (in terms of kilobytes). For instance, the file 6_bytes.txt actually takes up 4 kilobytes of actual storage space - as denoted in its first column. 

In short,  'ls -l' provides actual number of data bytes contained within a file while 'du' provides the block count consumed (= actually used) by the file from the filesystem.

No comments:

Post a Comment