Skip to content

Instantly share code, notes, and snippets.

@m-butterfield
Last active Sep 26, 2015
Embed
What would you like to do?
#!/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