You seem to correctly invoke the history -a
command before each prompt by making it part of the $PROMPT_COMMAND
string. This will append the current in-memory history to the history file.
However, appending the history to the history file will not automatically read the updated history from the same file, so you will need to do that separately using history -n
. This command will "read all history lines not already read from the history file
and append them to the history list" (that's from help history
in the shell). The "history list" is the in-memory command line history.
That means:
PROMPT_COMMAND="history -a; history -n; $PROMPT_COMMAND"
Or, if you want to clear the in-memory history before re-reading all of the history from the history file (you may want to use this if you find that the above gives you an unintuitive ordering of commands in the history):
PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"
Note that if you source
the .bashrc
file several times, you will add more and more to the $PROMPT_COMMAND
string. If you are in a habit of doing this, it would potentially be better to do it like this instead:
original_prompt_command=${original_prompt_command-$PROMPT_COMMAND}
PROMPT_COMMAND="history -a; history -n; $original_prompt_command"
This sets the value of the variable original_prompt_command
to the value of the PROMPT_COMMAND
variable, if original_prompt_command
is unset. This new variable is then used to update PROMPT_COMMAND
. The effect is that if the file is sourced more times, the original $PROMPT_COMMAND
value will always be extended and you will not get a longer and longer string.
PROMPT_COMMAND
to usehistory -a; history -c; history -r
instead, you'll find that history from other terminals is added after you press Enter and get a new prompt. But bash really doesn't do updating state in the background. You still need to get a new prompt. – muru Jan 24 '24 at 07:58