Tiny Code

Tiny Code

Saturday, February 21, 2015

Bash history

I've always had a strong preference for using command lines interfaces (AKA CLIs) over GUIs.  I can get tasks accomplished much faster using a Unix bash shell than I can on any GUI.  Plus CLIs lend themselves to greater levels of customization than GUIs do.  If I can customize a user interface, I can adapt it to the way I prefer doing things which makes the CLI even faster to use.

One of the customizations I use in Unix style shell interfaces is to modify how commands are stored in the shell command history.  I prefer the Bash shell (AKA Bourne Again Shell).  If you don't understand the humor in that, a little time on Google can clear it up for you.

The first step I took is to specify a permanent file for my shell history.  This allows multiple shells to share the same command history which frees me from the need to remember which shell I entered a command of interest into so I can recall it.  The following lines in a .bashrc file will set this for me.

# override default history size and file settings
export HISTSIZE=500
export HISTFILESIZE=500
export HISTFILE=~/.bash_history

I also need to prevent my history from being wiped out when a shell is closed.

# prevent closing a shell from overwriting history
shopt -s histappend

I also find it helpful to store timestamps for each command stored in the history.  This can be useful for shared computers where you may not be the only user entering commands.



# Store timestamp information for each command
export HISTTIMEFORMAT="%m%d %T  "





I also hate seeing duplicate commands in my command history.  One of each is sufficient and any more than that just clutter up the history unnecessarily.

# don't store duplicate commands
export HISTCONTROL=ignoredups:erasedups

And last but not least, I hate to waste space in my command history for short commands.  Typing ls is faster than looking it up in the command history so why waste space that could be storing more complicated commands that are harder to remember?

# ignore certain commonly issued commands
export HISTIGNORE=ls:ps:pwd






These lines added to your .bashrc should work on Linux, Cygwin under Windows, or Mac OS X terminal sessions.

1 comment:

Chard said...

HISTCONTROL! I've been trying to figure out why SOME of my Linux systems wipe out the duplicate commands and others don't, but I've never tracked down the environment variable that controls it. Thanks!