Linux Tips: take control of your bash_history

I spend most of my time working in front of a black and white terminal of remote SSH connections to various servers. This means that I use bash (as my preferred shell) most of the day. And bash history is a very important feature of bash that saves me much time by recalling previous commands I have typed. Here are some tricks on how you can optimize with some simple configurations settings the usage your bash history.

1. Don’t save duplicates: This is my favorite…

HISTCONTROL=ignoreboth

this causes any lines matching the previous history entry not to be saved. Other options for HISTCONTROL: ignorespace, lines which begin with a space character are not saved in the history list; erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved.

2. Size of the history: HISTSIZE: The number of commands to remember in the command history. The default value is 500.

HISTSIZE=500

You can set this to 0 and disable the usage of the history file.

3. Others: HISTFILE: The name of the file in which command history is saved. The default value is ~/.bash_history. HISTIGNORE: A colon-separated list of patterns used to decide which command lines should be saved on the history list.

How do you set these options? Either export them in your environment in your personal bash configuration file (~/.bashrc) or in the global bash configuration file (/etc/bash.bashrc). The name of the configuration files can depend from your Linux distribution and bash version (the ones included are from Debian Linux), but you can always see your particular options using man bash. So, you can add in your configuration files the parameters you want like this:

export HISTCONTROL=ignoreboth
export HISTSIZE=500

You will need to restart your bash session in order to activate the settings. You can check if your configuration were entered correctly by typing env at the command prompt. If you don’t see your configuration in the environment variables than you have done something wrong. If you see your configuration option, then all is ok, and your setting is active already.

Note: to my students (Bogdan and Alin) that attend my Linux Sysadmin course, I hope that this responds your question. Let me know if you have any other questions regarding this issue.

Here is a great note by one Digg user: burke “the most efficient way to search your history is to hit Ctrl R and type the start of the command. It will autocomplete as soon as there’s a match to a history entry, then you just hit enter”

comments powered by Disqus