Wednesday, 16 July 2014

Combine bash history across multiple terminals



I use tmux (and many people also use screen) for multiple terminals. On slight down side is that by default the history command does not remember the commands between sessions on the same server. After some research and experimenting I found the following works really well in my .bashrc :

export HISTFILE=~/.bash_history
export HISTFILESIZE=500000
export HISTSIZE=500000

export HISTCONTROL=ignoredups:erasedups
shopt -s histappend
unset PROMPT_COMMAND
export PROMPT_COMMAND="history -n;
history -w;history -c;history -r;$PROMPT_COMMAND"

Using 'Ctrl + R' will have the previous entries.

Note - if you are on session A run a command and move to session B you must either just press enter or another command before the entry in session A appears

Here is each line with some comments

  • Define where the history file is saved
export HISTFILE=~/.bash_history
  • How many commands to save in the HISTFILE
export HISTFILESIZE=500000
  • How many commands to save in the current session
export HISTSIZE=500000
  • Do not save duplicate commands and erase any previous duplicates
export HISTCONTROL=ignoredups:erasedups
  • How the history list is written to the HISTFILE. The '-s' option sets the option to append the history list of the current session to HISTFILE
shopt -s histappend
  • Clear current value of PROMPT_COMMAND
 unset PROMPT_COMMAND
  • Contents of PROMPT_COMMAND are run just before Bash displays a prompt. This will save and reload the history after every command
  •  -n : Append the new history lines
  •  -w : Write history which will cause 'erasedups' to occur
  •  -c : Clear the history list
  •  -r : read the current history file 
export PROMPT_COMMAND="history -n;history -w;history -c;history -r;$PROMPT_COMMAND"


 Hope you find this as useful as I have :)

No comments:

Post a Comment