Keep your bash history clean using python

If you are someone who spend a lot of time in terminal, you might want not to have certain commands that you’ve used, in your bash history. The commands like ‘ls’ which prints the contents of the directory to the standard output, or the terminal based games like “Moon Buggy” or “2048-cli” etc, the things which are not important enough and don’t have too complex commands to be stored in the bash history.

If you are interested in this, you can achieve this pretty easily by adding an EXIT Trap to your bashrc and writing a very simple python script (actually this doesn’t have to be a python script, I’ve done it using python; but you can use whichever language you are comfortable with).

Okay, so let’s get on to it.

Add EXIT trap to your .bashrc

EXIT trap:

There is a simple, useful idiom to make your bash scripts more robust -ensuring they
always perform necessary cleanup operations, even when something unexpected goes wrong. 
The secret sauce is a pseudo-signal provided by bash, called EXIT, that you can trap;
commands or functions trapped on it will execute when the script exits for any reason. 

source

To add this exit trap all you need to do is add the following code to your bashrc.

    function finish {
      # Your cleanup code
      ./.exit_script
    }
    trap finish EXIT

Once this is done, your exit_script will be called each time you exit the terminal window.

write an exit_script.

In the exit_script, (since I’m using python) the python code looks like

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

with open('.bash_history') as bh:

  to_be_deleted = []
  data = bh.read() #read the .bash_history file
  if data:
    lines = data.split('\n') #get the list of all commands
    for i in range(len(lines)): #iterate over all commands
      stripped = lines[i].strip(' ') #remove the starting spaces.
      #print i
      if (stripped == "ls" or stripped.startswith('2048')): #check if you need to delete this entry
        to_be_deleted.append(i) #if yes then add it to the list for commands to be deleted.


#write all the entries to the bash_history except those which are in the to_be_deleted list.
with open('.bash_history', 'w') as b_clean:
  for i in range(len(lines)):
    if i in to_be_deleted:
      #print(lines[i])
      pass
    else:
      if not lines[i]  == '':
        b_clean.write(lines[i]+'\n')

Save this file as “.exit_script” and make this file executable using the following command.

chmod +x .exit_script

Now “.exit_script” will be executed each and every time the terminal window is closed.

This way you can get rid of unnecessary entries in the bash history.