Skip to content

Instantly share code, notes, and snippets.

@ostechnix
Last active November 25, 2023 13:46
Show Gist options
  • Select an option

  • Save ostechnix/7f93a7acb8607929c28974c9c2db6e69 to your computer and use it in GitHub Desktop.

Select an option

Save ostechnix/7f93a7acb8607929c28974c9c2db6e69 to your computer and use it in GitHub Desktop.
Command Frequency Analyzer (CFA) - A simple Python script to display either the most frequently or least frequently used commands in Linux.
import os
from collections import Counter
def get_history_file():
shell = os.path.basename(os.getenv('SHELL'))
if shell == 'bash':
return os.path.expanduser('~/.bash_history'), 'bash'
elif shell == 'zsh':
return os.path.expanduser('~/.zsh_history'), 'zsh'
elif shell == 'fish':
return os.path.expanduser('~/.local/share/fish/fish_history'), 'fish'
else:
return None, None
def parse_commands(history_file, shell_type):
commands = []
with open(history_file, 'r') as file:
for line in file:
if shell_type == 'bash' or shell_type == 'zsh':
parts = line.strip().split()
if parts:
commands.append(parts[0])
elif shell_type == 'fish':
if line.strip().startswith('- cmd:'):
commands.append(line.strip().split(': ')[1])
return commands
def main():
history_file, shell_type = get_history_file()
if not history_file or not os.path.exists(history_file):
print("History file not found for the current shell.")
return
commands = parse_commands(history_file, shell_type)
command_count = Counter(commands)
choice = input("Do you want to display the 'most' used or 'least' used commands? Enter most/least: ").lower()
if choice not in ['most', 'least']:
print("Invalid choice. Please enter 'most' or 'least'.")
return
try:
num_commands = int(input("Enter the number of commands to display: "))
except ValueError:
print("Please enter a valid number.")
return
print(f"\nTop {num_commands} {choice} used commands:")
if choice == 'most':
for command, count in command_count.most_common(num_commands):
print(f"{command}: {count}")
elif choice == 'least':
for command, count in command_count.most_common()[:-num_commands-1:-1]:
print(f"{command}: {count}")
if __name__ == "__main__":
main()
@ostechnix
Copy link
Author

ostechnix commented Nov 24, 2023

Display Most Frequently or Least Frequently Used Commands using CFA in Linux:

Display Most Frequently or Least Frequently Used Commands using CFA in Linux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment