Unlimited bash history

Short:

@ /etc/bash.bashrc:

export HISTTIMEFORMAT="%y%m%d%H%M%S "
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $ $USER "$(history 1)" >> $HOME/.bash_eternal_history'

@ bash commandline:

cat > $HOME/bin/myhistory.sh
#!/bin/bash

awk '!a[$0]++' ~/.bash_eternal_history
^D

Long:

Generally speaking, it’s very useful to have the history of all commands you have ever typed. However bash keeps only a limited number of commands.There are two environment variables, HISTSIZE and HISTFILESIZE [bash(1)] which define the maximum number of commands and the maximum number of lines in the history file. In theory, there is no upper bound to the value you can assign to them. In real life though, mysterious vanishment of history data file has been reported around.

A workaround for this, is defining the envirnment variable  PROMPT_COMMAND [bash(1)]. A good idea is to define it at the central bashrc file of the system,  /etc/bash.bashrc, so that unlimited history will be available for all users:

export HISTTIMEFORMAT="%y%m%d%H%M%S "
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $ $USER "$(history 1)" >> $HOME/.bash_eternal_history'

The first line defines the format of the date. The second line, for each expression that we type, tells bash to print the process id ($$) of current bash session, the username ($USER) and the last line of bash history, which is what we just typed. When we cat the file that our unlimited history is stored, we notice that there are a lot of multiple records of the same command. This happens because when we simply press “enter”, the expression   $(history 1)   has always the value of the last command we typed. We workaround this by creating a little script and use that as a history command:

#!/bin/bash

awk '!a[$0]++' ~/.bash_eternal_history

In this, awk [awk(1)] filters out the duplicated lines.


Reference: