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?
Asked
Active
Viewed 805 times
0

Dawson Smith
- 473
- 1
- 6
- 15
-
du: Show usage for each file or directory. sort: Reverse sort in numeric order, bringing the largest ones on top. head: Show the first few. – n. m. could be an AI Jan 04 '22 at 09:46
-
Can you explain with all the flags? And the intermediate steps? What happens first and how data is passed from du to sort to rn? – Dawson Smith Jan 04 '22 at 09:48
-
The `|` character (called *pipe*) takes the output of the preceding command and sends it to the input of the following command. Type `man du` to read about `du` flags. – n. m. could be an AI Jan 04 '22 at 09:53
-
There's a star(*) also in between. Can you explain a bit more? – Dawson Smith Jan 04 '22 at 10:08
-
Will the above command recursively check in all folders? – Dawson Smith Jan 04 '22 at 10:14
1 Answers
1
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

ceving
- 21,900
- 13
- 104
- 178