How To: Find top used shell comamnds (Linux, macOS)

Do you know which shell commands do you type more often than others? Do you have any idea which aliases need to be added to save your typing time? With the power of piping and four simple tools, you will be able to answer these questions in a second. Here is a command:

history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head -n 10

Explanation:

  • history - a utility which prints all commands you ever typed
  • awk - is a super-powerful data extraction tool. In this case, it extracts unique commands and counts the number of usages. I really recommend learning how to use it: The GNU Awk User’s Guide
  • sort - sorts lines
  • head - takes only top lines and discards the rest

And output:

1322 kubectl
574 nano
546 gst
487 ggp
441 cd
400 gl
372 gcam
284 curl
256 ssh
241 gcm

The output contains two columns: number of command usages and command. For example, in this output, the top line is kubectl and it should have shorter alias to save typing time.

That is all I have to say. I hope that this small tip will bring you closer to being a better developer.