Here I will point out one problem with
export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r"
and
PROMPT_COMMAND="$PROMPT_COMMAND;history -a; history -n"
If you run source ~/.bashrc, the $PROMPT_COMMAND will be like
"history -a; history -c; history -r history -a; history -c; history -r"
and
"history -a; history -n history -a; history -n"
This repetition occurs each time you run 'source ~/.bashrc'. You can check PROMPT_COMMAND after each time you run 'source ~/.bashrc' by running 'echo $PROMPT_COMMAND'.
You could see some commands are apparently broken: "history -n history -a". But the good news is that it still works, because other parts still form a valid command sequence (Just involving some extra cost due to executing some commands repetitively. And not so clean.)
Personally I use the following simple version:
shopt -s histappend
_bash_history_append() {
builtin history -a
builtin history -c
builtin history -r
}
PROMPT_COMMAND="_bash_history_append;${PROMPT_COMMAND#"_bash_history_append;"}
which has most of the functionalities while no such issue as mentioned above.
It is good to prepend _bash_history_append
to default PROMPT_COMMAND
, because in default
we can have something like __vte_prompt_command
, which will keep current directory when opening
new tabs in gnome-terminal etc.
So we remove prefix _bash_history_append
from PROMPT_COMMAND
and so there are no repetitions.
Another point to make is: there is really nothing magic.
PROMPT_COMMAND is just a plain bash environment variable. The commands in it get executed before you get bash prompt (the $ sign). For example, your PROMPT_COMMAND is "echo 123", and you run "ls" in your terminal. The effect is like running "ls; echo 123".
$ PROMPT_COMMAND="echo 123"
output (Just like running 'PROMPT_COMMAND="echo 123"; $PROMPT_COMMAND'):
123
Run the following:
$ echo 3
output:
3
123
"history -a" is used to write the history commands in memory to ~/.bash_history
"history -c" is used to clear the history commands in memory
"history -r" is used to read history commands from ~/.bash_history to memory
See history command explanation here: http://ss64.com/bash/history.html
PS: As other users have pointed out, export is unnecessary. See: Using export in .bashrc
export PROMPT_COMMAND="history -a; $PROMPT_COMMAND"
. Existing shells will add each command to the history file for new shells to see, but only show their own histories. – Chris Page Sep 28 '11 at 08:34flock
. Unfortunately even that is not quite 'atomic'; often the mutex fails gracefully (as intended; most often when the system re-opens terminals following a power-up); but (very rarely) it also fails gracelessly, and results in an empty (shared) history file. (So, I periodically make a copy and a backup. I should try debugging further…) – Rhubbarb Mar 02 '17 at 10:00