unexpected behavior bash, set -o vi, history -a, and HISTFILE

I am trying to get my history in sync in multiple bash sections and things aren't working the way I expect.

Desired behavior, hitting esc-K in all bash sessions (same userid and machine) will use the same history.

Observed behavior: Esc-k shows the history of the current session, rather than the latest command in the HISTFILE. I can see my last command being appended to the HISTFILE, but esc-K only scrolls through the current session's history.

Here are some of my env settings:

$ set|grep -i hist
HISTFILE=/home/histories/gharari/.sh_history
HISTFILESIZE=999999
HISTSIZE=999999
HISTTIMEFORMAT='%a %x %r '
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\007";history -a'
SHELLOPTS=braceexpand:hashall:histexpand:interactive-comments:monitor:vi

Thanks for helping me figure this out.

HISTFILE does not work that way. It is written when your interactive shell quits.

Unless you issue a `history -a` after each command, which I am in my PROMPT_COMMAND.

Here is something that might suit your needs: pts.blog: How to automatically synchronize the shell history between terminal windows

1 Like

+1

---------- Post updated at 11:47 AM ---------- Previous update was at 11:34 AM ----------

This is a smart solution. A bit complicated, but smart. I wish that bash could do this on it's own. I am a bit weary about finding a bug down the road with the trap and re-execution of the command. Also, potential debugging of what is happening to the modified environment variables. I am sure it works, but just too much hacking going on for the sake of syncing sessions.

This is one of the reasons I'm always using ksh when available.

Is the behavior different in ksh?

I won't dare to say for all the ksh versions there are out there, but the ones i have used (working mainly on AIX) do that automatically. Every command immediately goes into the history file and history always works on this file. It is possible to assign different history files to different shell invocations to avoid that behavior if you don't want it.

The variable "HISTFILE" controls the location of the history file (HISTSIZE controls its size in # of lines) and per default it points to "~/.sh_history". If you want separate history files for every shell you could put the following into your "~/.kshrc" file. By appending the (unique) process ID to the file name a new history file is created for every "ksh" invocation:

HISTFILE="${HOME}/.sh_history_$$"

I hope this helps.

bakunin

pdksh, like bash, is writing the history file at shell exit when HISTFILE is set. By default, it is not even saving its history.

Real ksh (ksh88 & ksh93) are doing synchronous history writes so are not suffering bash/pdksh annoying behavior.