Bash history handling with multiple terminals

The bash session that is saved is the one for the terminal that is closed the latest. If you want to save the commands for every session, you could use the trick explained here.

export PROMPT_COMMAND='history -a'

To quote the manpage: “If set, the value is executed as a command prior to issuing each primary prompt.”

So every time my command has finished, it appends the unwritten history item to ~/.bash_history before displaying the prompt (only $PS1) again.

So after putting that line in /etc/bash.bashrc I don’t have to find myself reinventing wheels or lose valuable seconds re-typing stuff just because I was lazy with my terminals.

Anyway, you'll need to take into account that commands from different sessions will be mixed in your history file so it won't be so straightforward to read it later.

See also:

  • https://unix.stackexchange.com/questions/1288/preserve-bash-history-in-multiple-terminal-windows

After multiple readings of man bash, I use separate history files for each shell. I did a mkdir -m 0700 ~/.history then added

[[ -d ~/.history ]] || mkdir --mode=0700 ~/.history
[[ -d ~/.history ]] && chmod 0700 ~/.history
HISTFILE=~/.history/history.$(date +%y%b%d-%H%M%S).$$
# close any old history file by zeroing HISTFILESIZE  
HISTFILESIZE=0  
# then set HISTFILESIZE to a large value
HISTFILESIZE=4096  
HISTSIZE=4096  

to my ~/.bashrc. Every now and then, I remember to du -sk .history and clean it out. It's nice to have every command I've typed preserved for me.

I just used the above to see what I'd been doing, of late:
cut -f1 "-d " .history/* | sort | uniq -c |sort -n -r |less
or
cut -f1-2 "-d " .history/* | sort | uniq -c |sort -n -r |less
(to include the 1st argument e.g. sudo mount in the sort chain).


To show history from all terminals:

Add export PROMPT_COMMAND='history -a; history -r' to your .bashrc file.

Source: http://northernmost.org/blog/flush-bash_history-after-each-command