Bash – Use bash history file from old machine when setting up new machine

bashcommand history

I love my bash history. Sometimes I've issued really long commands and I really depend on my bash history to get them back quickly. I've increased my history size with:

HISTSIZE=100000
HISTFILESIZE=200000

in my .bashrc

I also have aliases:

alias h='history | tail'
alias hg='history | grep'

which allow me to do h and hg some_text which is really handy

My question is: Can I move this history file to a new machine? For instance my machine recently crashed and I had to rebuild it. Would I have any issues dropping a different .history file in, possibly replacing the one already there. Do I need to make sure to replace it or can I actually append two history files together without issue?

Best Answer

Yes. You can copy the old history file to a new install. You can also merge it with old / new.

  • If you do not have HISTTIMEFORMAT set the history file only holds commands.
  • If it is set there is a timestamp preceded by a hash for each command:

    #1122334455
    command1
    #1122334459
    command2
    

Note however that if you issue e.g:

$ echo 'foo
> bar
> baz' >> some_file

It is going to be saved as:

#1122334459
echo 'foo
bar
baz' >> some_file

But history is going to show:

4 CMD_TIME echo 'foo
5 CUR_TIME bar
6 CUR_TIME baz' >> some_file

Commands like:

$ foo | \
bar | \
baz

are preserved as one if you set shopt -s cmdhist.


I use various but often something like:

HISTSIZE=500000
HISTFILESIZE=500000
# Ignore dupes and space commands
HISTCONTROL=ignoreboth
# Save and show timestamps
HISTTIMEFORMAT='%F %T '
# append to the history file, don't overwrite it
shopt -s histappend
# Save and reload the history after each command finishes
# This one I have a function to turn on/off. Effect is that commands are
# accessible in all terminals after execution.
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"

I also back up history files regularly and have some scripts and aliases to search history – even many years back in time. Sometimes I recall I did something similar to what I'm currently doing 1.5 years ago and can quickly look up in history.

As for timestamps I use two variants. history shows with timestamps and another show without by temporarily setting HISTTIMEFORMAT to "".


If timestamp is missing current time (approximately) is used. If timestamps are present history is sorted by times.

Thus:

.bash_history (Timestamps simplified)

#timestamp 000012
some command
#timestamp 000002
some other command

$ history
1 13 aug 2013 10:44 some other command
2 13 aug 2013 12:13 some command

It is however reasonable to believe that a sorted history file is more effective (bash doesn't have to do any shuffling).


As for lookup Ctrl-R is often useful. For other things look at e.g. Commands For Manipulating The History, Event Designators, Some Miscellaneous Commands etc.

Related Question