By default, history is stored in the file ~/.bash_history, we can change ~/.bashrc
Sync Bash History Between Terminals
shopt -s histappend
: when close a session, the history will be appended to the .bash_history file rather than overwriting.
Increase Bash History Size
- HISTSIZE: the number of lines or commands that are stored in memory in a history list (the default value is 500).
- HISTFILESIZE: the maximum number of lines contained in the history file (the default value is 500).
Store bash history immediately
PROMPT_COMMAND="$PROMPT_COMMAND; history -a"
- Store but don’t reload, so Up/Down is per shell.
PROMPT_COMMAND="PROMPT_COMMAND; history -a; history -c; history -r;"
- Store and reload the history immediately
- PROMPT_COMMAND: if set, it’s executed before the printing of each primary prompt ($PS1)
history
- -a: Append the new history lines to the history file
- -c: Clear the history list.
- -r: Read the current history file and append its contents to the history list.
- -n: Append the history lines not already read from the history file to the current history list
Use one command per line
shopt -s cmdhist
: Store multi-line commands in one history entry
Add date and time to bash history
HISTTIMEFORMAT="%h %d %H:%M:%S "
HISTCONTROL: how commands are saved
HISTCONTROL=ignorespace:erasedups
| | | |:———– |:—————————————————– | | ignorespace | don’t save lines which begin with acharacter | | ignoredups | don’t save lines matching the previous history entry | | ignoreboth | use both ‘ignorespace’ and ‘ignoredups’ | | erasedups | eliminate duplicates across the whole history |
HISTIGNORE: Ignore specific commands
HISTIGNORE="history"
Others setting about bash history
- HISTFILE: change the history file name, the default value is ~/.bash_history.
History searching
- with the below setting, we save bash history across all terminals.
- Up/Down to scroll back and forward
- ^R: search the typed substring in all history entries
history | grep xx
: quickly search and find commands we ran before.
The Complete Setting for Bash History
# append to the history file rather than overwrite it
shopt -s histappend
HISTSIZE=9999999
HISTFILESIZE=9999999
# Store and reload the history immediately
PROMPT_COMMAND="PROMPT_COMMAND; history -a; history -c; history -r;"
# use one command per line
shopt -s cmdhist
HISTTIMEFORMAT="%h %d %H:%M:%S "
HISTCONTROL=ignorespace:erasedups
HISTIGNORE="history"