Home > Uncategorized > Keeping your bash history

Keeping your bash history

One thing I want to remember to do every time I set up a new Unix account or machine is setup bash so that it remembers all my commands.  This may be accomplished by adding


export HISTCONTROL=erasedups
export HISTSIZE=100000
shopt -s histappend

to my shell init. The first one eliminates duplicates from shell history. The second raises the history length from 500 to 100,000 (I wonder if the limit can be removed altogether?). And the third one makes it so that history is appended. That way separate shell sessions don’t clobber each other.

This raises the question, exactly which file is the shell init?  Is it /etc/profile, /etc/bashrc, /etc/bash.bashrc, ~/.bash_profile, ~/.bash_login, ~/.profile, or ~/.bashrc? I am perpetually confused about this. I’m pretty sure you’re supposed to set your PATH in one of these files, not the others.  The profile files (/etc/profile, ~/.bash_profile, ~/.bash_login, and ~/.profile) are for login shells only (/etc/profile for all users of the system and ~/.bash_profile, ~/.bash_login, and ~/.profile for just the single user account), but if you’re setting environment variables and use the export command, then those variables are inherited by all shells (assuming that all shells are descended from a login shell.  Is that true?).  So it’s fine that my PATH is set in my ~/.profile.  All subshells will inherit.  This will also work for HISTCONTROL and HISTSIZE.  But what about the shopt built-in?  If I set that in ~/.profile, subshells will not inherit the histappend option.  I believe (but am not positive) that I do want all history saved, even subshells (for example, this means if I write a bash script and execute it, all the commands in the script will be saved to my history.  That doesn’t seem too desirable, but it’s always better to err on the side of saving data, rather than losing data, right?).  But if I put it in ~/.bashrc, then login shells won’t have it.  Why isn’t there a shell setup for _all_ shells?  Should I put it in my ~/.profile, and then source that in my ~/.bashrc?  But this would destroy the ability to distinguish the two use modes.  I guess I will just add the command to both ~/.profile and ~/.bashrc.

A shell without these flags turned on has broken history. It’s a must-do. I had turned these on in my MacBook Pro, but a while back the HDD failed, and it got re-imaged by the Apple Genius. I never turned it back, so now I’m missing some history that I need access to. Mental note: always do this.

Via the macromats blog.

Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.