1

Print the 10 most used commands with their counts

history | awk '{print $2}' | sort | uniq -c | sort -nr | head

April 5, 2019Julien_Tremblay_McLellan

Explanation

Example output:

30 cat
15 shopt
15 alias
14 vim
14 date
14 bash
11 man
11 history
11 bind
10 ls
  • history prints the command history, each line prefixed with an index (the first command ever executed has index 1, the second has index 2, and so on)
  • | awk '{print $2}' prints the second field of the input. For example for the history line 5 echo $BASH_VERSION, this would output echo
  • | sort sorts the lines in the input; this becomes important for the next command in the pipeline
  • | uniq -c filters repeated lines (only showing a line once), the -c flag makes it prefix lines with the number of times they appear in the input. For example a line that is not repeated, the count is 1. It's important to know that uniq compares only adjacent lines, so if the same line appears multiple times in the input but in different places, they will not count as repeats. This is why we sorted the input in the previous step.
  • | sort -nr sorts the input in numeric order, and prints them in reverse. As we have lines prefixed with their counts, this will effectively print the line with the highest count first, the second highest second, and so on.
  • | head prints the first 10 lines of the input

And there you have it: the pipeline comes together to show the top 10 most used commands with their counts.