Skip to content

Instantly share code, notes, and snippets.

@MatthewScholefield
Last active January 5, 2024 22:09
Show Gist options
  • Save MatthewScholefield/ab07199f8a140143ecd2a0bfb3aa5980 to your computer and use it in GitHub Desktop.
Save MatthewScholefield/ab07199f8a140143ecd2a0bfb3aa5980 to your computer and use it in GitHub Desktop.
ZSH history truncator

ZSH History Pruner

Overview

When using ZSH as a shell, the history file can become cluttered with long commands that were accidentally pasted into the terminal. This particularly becomes problematic when you increase the history size since reverse search can begin to take multiple seconds to complete. This script addresses this problem by letting you easily prune your ZSH history.

Usage

git clone <gist_url> zsh-history-pruner
python3 zsh-history-pruner/prune_zsh_history.py ~/.zsh_history pruned_zsh_history --char-limit 6000

# Validate pruning result is acceptable
du --human --apparent-size ~/.zsh_history pruned_zsh_history

# Repplace current ZSH history with pruned file
cp ~/.zsh_history ~/.zsh_history.bak
exec mv pruned_zsh_history ~/.zsh_history

License

This script is released under public domain.

import argparse
def process_history(input_file, output_file, char_limit):
prune_count = 0
with open(input_file, 'rb') as infile, open(output_file, 'wb') as outfile:
current_entry = b''
for line in infile:
current_entry += line
if not line.endswith(b'\\\n'): # End of an entry
if len(current_entry) <= char_limit:
outfile.write(current_entry)
else:
prune_count += 1
current_entry = b''
print('Pruned', prune_count, 'entries.')
def main():
parser = argparse.ArgumentParser(description='Filter zsh history file.')
parser.add_argument(
'input_file', type=str, help='Input zsh history file path'
)
parser.add_argument(
'output_file', type=str, help='Output zsh history file path'
)
parser.add_argument(
'--char-limit',
type=int,
default=6000,
help='Character limit for removal (default: 6000)',
)
args = parser.parse_args()
process_history(args.input_file, args.output_file, args.char_limit)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment