[colug-432] Search Command History

Rob Funk rfunk at funknet.net
Tue Feb 11 09:46:23 EST 2014


Eric Floehr wrote:
> >
> > Is there something I'm missing that will cause this to get written more
> > immediately than on a proper logout?  I've run into several situations
> > where I really needed to see that history to know what someone else was
> > doing, or where I left off, or what that complex sed command was - but I'm
> > out of luck.
> >
> 
> Yes, put this in your .bashrc:
> 
> PROMPT_COMMAND="${PROMPT_COMMAND:-:} ; history -a; history -n"
> 
> At every prompt it will append to the history file commands run since the
> last time it was appended.

I'll just note that the reason such contortions are required is that
normally the shell writes the history file only on exit. Which is also
why "history | grep foo" is more likely to find your earlier command
than "grep ~/.bash_history".

(Search the bash man page for "HIST" for lots more details on this
stuff. For example, HISTTIMEFORMAT is a useful thing to set.)

> The second, history -n, is optional... it will reread the history file.
> 
> Note that multiple shells will have their history intermingled, so you do
> run into a few problems up-arrowing and not always seeing a coherent past.
> I've removed history -n for that reason on my shells.
> 
> Also, you might find histappend needs set (put this also in your .bashrc):
> 
> shopt -s histappend

Hm, I should consider those options....

I usually have multiple shells open to the same machine at once, so
the history saved to the file is only from the last one to exit, which
means I lose the history from the other shells. I've started
experimenting with setting HISTFILE using the output of the "tty"
command, but haven't settled on something I'm sure I like yet. I think
this is my latest iteration in .bashrc on one machine:
HISTFILE="$HOME/.bash_history-$( tty | sed -e 's,/dev/,,' -e 's,/,_,g' )"



More information about the colug-432 mailing list