linuxdisk-access

Meaning of the statement - du -sk * |sort -rn|head


I am facing trouble understanding the meaning of the Linux command du -sk * |sort -rn|head. I understand that du is used to display the disk usage but I'm facing trouble understanding the rest of the command. Can somebody please breakdown what's exactly happening here? Also can some good resources be suggested for studying complex linux commands in detail?


Solution

  • Good resources to study Unix commands are the manual pages.

    man du:

    Summarize disk usage of the set of FILEs, recursively for directories.
    -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
    -k     like --block-size=1K
    -s, --summarize
           display only a total for each argument
    

    man sort:

    Write sorted concatenation of all FILE(s) to standard output.
    -r, --reverse
           reverse the result of comparisons
    -n, --numeric-sort
           compare according to string numerical value
    

    man head:

    Print  the  first  10 lines of each FILE to standard output.  With more
    than one FILE, precede each with a header giving the file name.
    

    The command shows the 10 largest directories or files.

    Step by step:

    #! /bin/bash
    
    echo 'Create 20 files with random size.'
    for i in {1..20}; do
      dd if=/dev/zero of="$i".data bs=1k count="$RANDOM"
    done
    
    echo 'Show the size of all 20 files in default units.'
    du -s *.data
    
    echo 'Show the size of all 20 files in KB.'
    du -sk *.data
    
    echo 'Show the size of all 20 files in KB and sort it in numeric order.'
    du -sk *.data | sort -n
    
    echo 'Show the size of all 20 files in KB and sort it in reverse numeric order.'
    du -sk *.data | sort -rn
    
    echo 'Show just the first 10 files of the previous output.'
    du -sk *.data | sort -rn | head