The bash shell maintains a history
of the commands you entered. You can re-execute a command by recalling it from
the history, without having to re-type it.
The command history is stored in a file, specified by an environment variable.
$ echo $HISTFILE
/home/user/.bash_history
The maximum number of commands that it will save depends on the value of this environment variable:
$ echo $HISTSIZE
500
The command history is stored in a file, specified by an environment variable.
$ echo $HISTFILE
/home/user/.bash_history
The maximum number of commands that it will save depends on the value of this environment variable:
$ echo $HISTSIZE
500
Life is simple if we operate on a single shell session at any given time. If you have 2 simultaneous sessions, you may be surprised that the history does not have the commands you expect.
The default behavior is that the command history is saved ONLY on session exit. Moreover, the existing contents in the history are overwritten by the new contents.
Assuming you already have a session running, opening a second session will not have the latest commands from the first session. This is because the first shell hasn’t exited yet. Ultimately, the contents of the history file depends on which session exits last, hence overwriting the commands from the session that finishes earlier.
This can become quite confusing.
The remedy is simple. Change the history behavior as follows:
- Append
commands to the history file, rather than overwrite it.
$
shopt -s histappend
- Save each command right after it has been executed, not
at the end of the session.
$
PROMPT_COMMAND='history -a'
Insert the 2 statements into ~/.bashrc
shopt -s histappend
PROMPT_COMMAND='history -a'
Note: If the PROMPT_COMMAND is already initialized, then you probably want to concatenate the history -a part to what is already there.
To determine if PROMPT_COMMAND has a value:
echo
$PROMPT_COMMAND
To concenate:
PROMPT_COMMAND="history
-a;$PROMPT_COMMAND"