Search code examples
unixdash-shell

The largest file


I tried to print the largest file in a directory but I can't explain why I get 768 instead of 726491. $DIR is directory and $ext is file extension. My script should work in dash.

 find "${DIR}" -type f -name "*.$ext" -exec du -a {} + | 
 sort -n -r | head -n 1 | cut -f1

 768     ./subfolder/test.jpg

 -rw-r--r--  1 username  vti  726491 19 mar 12:46 test.jpg
 drwxr-xr-x  2 username  vti     512 19 mar 12:46 subsubfolder
 drwxr-xr-x  3 username  vti     512 19 mar 12:46 .
 drwxr-xr-x  4 username  vti     512 19 mar 12:46 ..

Solution

  • du, by default show disk usage as block size (1024 bytes / 512 bytes), not in bytes.

    If you want du to print bytes, you need to specify -b (or --bytes) option:

    find "${DIR}" -type f -name "*.$ext" -exec du -a -b {} + | ..
                                                     ^^
    

    Accoridng to DU(1):

       --apparent-size
              print apparent sizes,  rather  than  disk  usage;  although  the
              apparent  size is usually smaller, it may be larger due to holes
              in ('sparse') files, internal  fragmentation,  indirect  blocks,
              and the like
    
       -B, --block-size=SIZE
              scale  sizes  by  SIZE  before printing them; e.g., '-BM' prints
              sizes in units of 1,048,576 bytes; see SIZE format below
    
       -b, --bytes
              equivalent to '--apparent-size --block-size=1'
    

    UPDATE

    On system, where -b option is not supported, use -B 1 option instead:

    find "${DIR}" -type f -name "*.$ext" -exec du -a -B 1 {} + | ..
    

    UPDATE2 In FreeBSD, you need to specify -A option to display apparent size.