Skip to content

Instantly share code, notes, and snippets.

@ganwell
Last active October 8, 2015 03:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ganwell/3273360 to your computer and use it in GitHub Desktop.
Save ganwell/3273360 to your computer and use it in GitHub Desktop.
Bash history of unique commands
# 5000 unique bash history lines that are shared between
# sessions on every command. Happy ctrl-r!!
shopt -s histappend
# Well the python code only does 5000 lines
export HISTSIZE=10000
export HISTFILESIZE=10000
export PROMPT_COMMAND="history -a; unique_history.py; history -r; $PROMPT_COMMAND"
#!/usr/bin/python
import os
import fcntl
import shutil
import sys
file_ = os.path.expanduser('~/.my_history')
try:
f = open(file_, 'r')
lines = list(f.readlines())
f.close()
except (FileNotFoundError):
f = open(file_, 'w')
f.write('')
f.close()
lines = []
myset = set(lines)
file_bash = os.path.expanduser('~/.bash_history')
f = open(file_bash, 'r')
lines += list(f.readlines())
f.close()
lineset = set(lines)
diff = lineset - myset
if len(diff) == 0:
sys.exit(0)
sys.stdout.write("+")
newlist = []
lines.reverse()
count = 0
for line in lines:
if count > 5000:
break
if line in lineset:
count += 1
newlist.append(line)
lineset.remove(line)
f = open(file_, 'w')
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
newlist.reverse()
for line in newlist:
f.write(line)
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
f.close()
shutil.copyfile(file_, file_bash)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment