Top 20 bash commands in Python
#!/usr/bin/env python3
from collections import Counter
import matplotlib.pyplot as plt
import os
history_file = os.path.expanduser("~/.bash_history")
counter = Counter()
with open(history_file, "r", errors="ignore") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
cmdline = line.split("|", 1)[0].strip()
parts = cmdline.split()
if not parts:
continue
cmd = parts[1] if parts[0] == "sudo" and len(parts) > 1 else parts[0]
counter[cmd] += 1
top = counter.most_common(20)
commands, counts = zip(*top)
commands = commands[::-1]
counts = counts[::-1]
plt.figure(figsize=(10, 6))
plt.barh(commands, counts)
plt.title("Top 20 Bash Commands (frequency)")
plt.xlabel("Usage count")
plt.tight_layout()
plt.show()
