Skip to content

Instantly share code, notes, and snippets.

@m-butterfield
Last active September 26, 2015 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-butterfield/fddbbf690dfe3c30a56c to your computer and use it in GitHub Desktop.
Save m-butterfield/fddbbf690dfe3c30a56c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
top_history
Print the top 10 commands from your bash history
Usage:
top_history <user_name>
Options:
-h --help Show this screen.
"""
from collections import defaultdict
import os
import sys
from docopt import docopt
TOP = 10
def main(user_name):
command_counts = _get_command_counts(_get_history(user_name))
for i, command in enumerate(command_counts):
if i == TOP:
break
print command[0] + "\t" + str(command[1])
def _get_command_counts(commands):
command_counts = defaultdict(int)
for command in commands:
base_command = command.strip().split(' ')[0]
if not base_command:
continue
command_counts[base_command] += 1
return sorted(command_counts.items(), key=lambda x: x[1], reverse=True)
def _get_history(user_name):
path = '/home/' + user_name + '/.bash_history'
if not os.path.exists(path):
print "File not found: " + path
sys.exit(1)
with open(path) as fp:
return fp.readlines()
if __name__ == '__main__':
main(docopt(__doc__)['<user_name>'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment