1

I'm using a fresh install of Ubuntu 22.04.3, with gnome-terminal, and I haven't directly edited ~/.bashrc. Various sources say adding the following to it achieves what I'm looking for:

shopt -s histappend
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

I then source ~/.bashrc.

What I want is for the following to happen. I open two terminal windows. In the first, I execute echo 1. In the second I execute echo 2. In the first I press the up arrow, and I see echo 2. Instead what I see is echo 1. That's to say bash window history is kept separate from each other. If I close the windows, and then reopen one, then the histories are merged, but I want history to update for all windows as commands are executed.

How can I achieve this?

1
  • 1
    Bash is really not the shell for this. But: if you change PROMPT_COMMAND to use history -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 at 7:58

1 Answer 1

2

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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .