Making your BASH history more efficient

There are several ways to improve how you troubleshoot a system. One of the things I consider to be important is the BASH history. Here you can see what commands were executed. Though as default you can’t see when, or ignore certain things, like duplicate commands. Here’s a little guide to show you how.

HISTTIMEFORMAT

A simple yet effective little trick is to change the format of the output the command history spits out. In my case it comes to good use when troubleshooting a system, wanting to find out if errors in the system log match up with commands executed at that time. To enable the feature in your current terminal, run:

So the output from history that was looking like this:

Now looks like this:

 

HISTCONTROL

The variable HISTCONTROL can do a few things, like ignoring duplicates if they are in a row and erasing duplicates. The difference here is that by ignoring duplicates, it will remove duplicates only if they are in a row, while erasing duplicates, it will remove previous commands from the history file. Let’s give an example:

ignoredups

First run:

The output that looked like this:

Will now look like this:

 

erasedups

erasedups means that if you executed the same command previously, that entry will be erased, substituted by the newly run command. Generally not recommended though. If you still wish to do so, it can be done by running the following line:

So a history that looked like this:

After the export, will now look like this when we run the command pwd again:

 

ignorespace

If you want full control over which commands will be stored by history and which will not be stored, set HISTCONTROL to ignorespace:

So out of these commands:

Only these will show:

 

ignoredups and ignorespace

To use both of these features, simply use:

HISTIGNORE

The variable HISTIGNORE will help you tell history which commands to ignore, meaning that they shouldn’t be picked up by the BASH history. For instance, let’s say that I want the commands df and free to be ignored, including optional flags:

HISTSIZE

Setting how many lines of history to store is always a nice feature:

Thanks to pkhamre for suggesting to include HISTCONTROL and HISTIGNORE. ;)

Leave a comment