Shell Script to find the most commonly used commands

Preparing for writing a blog on the commonly used commands by me,I came out with a unique challenge. How can I find out my most frequently used commands?
Then I thought writing a shell script for that, Though I need not have one. The following at the command prompt will suffice

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


   24 vim
   23 gcc
    9 ./a.out
    5 ls

This will give all the commands along with their frequency of use

But still if I could find out the most commonly used n number of commands, that would be more advantageous. So here’s the shell script
So the usage of command is cmd_history [n]
n is an optional number

# To Display the frequency of commands so far used
#Usage: ./cmd_history [n]
# where n is a number(optional)

history | awk '{print $2}' | sort|uniq -c | sort -rg  >tmp.$$
if [ $# -ge 1 ]
   head -$1 tmp.$$
   cat tmp.$$
rm -f tmp.$$


$./cmd_history 3

$ 25 vim
23 gcc
9 ./a.out

NOTE: You can even use

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

without using the shell script where instead of 5, you can specify your own number

Also, this uses history of commands, so you should not have cleared your history of commands before using.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s